I'm trying to dynamically build a table that needs to be bound to a ViewModel on form submission.
First item is the Action the form is submitting to. Then the Parent ViewModel and then the child ViewModel. Below those are two text fields representing the data I need bound.
When I submit the form all the other fields from the page are bound to their respective property but the complex object of ProgramViewModels is not.
What am I missing?
public ActionResult Add(AddEntityViewModel viewModel){
Code that does something
}
public class AddEntityViewModel
{
public IList<int> Counties { get; set; }
public IList<ProgramViewModel> Programs { get; set; }
public IList<int> Regions { get; set; }
public string EntityName { get; set; }
public bool IsValid()
{
if (string.IsNullOrEmpty(EntityName))
return false;
if (Counties == null || Counties.Count == 0)
return false;
if (Programs == null || Programs.Count == 0)
return false;
if (Regions == null || Regions.Count == 0)
return false;
return true;
}
}
public class ProgramViewModel
{
public int Id;
public string SystemId;
}
<input type="hidden" id="Programs[0]__Id" name="Programs[0].Id" data-programid="3" value="3">
<input type="text" id="Programs[0]__SystemId" name="Programs[0].SystemId" style="width:100%" maxlength="50">
Update:
Changed the fields to properties after adiga's answer. But that too did not fix the issue.
public class ProgramViewModel
{
public int Id { get; set; }
public string SystemId { get; set; }
}
Programslist first? Shouldn't you initialize the list by doingPrograms = new List<ProgramViewModel>()in yourAddEntityViewModel? Also if you have to grab user's input dynamically from a form, I will just build the object from client side and use jQuery post ($.ajaxor$.post) to submit the form with the custom object. MVC is smart enough to bind the custom object to the view model you define.Programs[0].Idmakes me think you're using@Html.Helperto bind eachProgramViewModelto the form inputs. But then you mentioned in the post that you're trying to dynamically build the table. That's what confused me. If you want to submit dynamic data, you can't use@Html.Helperto bind the input values. It's better to just craft out the JavaScript object yourself on client side that matchs the view model on the Controller action and just do a Post back to server, without using form submit.