Tyddlywink
Tyddlywink

Reputation: 891

MVC Binding List of Objects in Object

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; }
}

Upvotes: 2

Views: 1575

Answers (2)

adiga
adiga

Reputation: 35222

Your ProgramViewModel contains fields. Change them to properties.

public class ProgramViewModel
{
    public int Id { get; set; }
    public string SystemId { get; set; }
}

The DefaultModelBinder uses reflection and binds only the properties and not fields.

Upvotes: 2

Gabriel Manzini
Gabriel Manzini

Reputation: 97

If you have a List of a object, you should be performing a foreach instruction to get all of them:

<% foreach(var x in values) { %>
<div>hello <%= x.name %></div>
<% } %>

Upvotes: 0

Related Questions