3

I have a class:

public class ClientInformation{
    public string UserName {get; set;}
    public ICollection<RegionDistrictCity> RegionDistrictCity
    {
        get;
        set;
    }

  public class RegionDistrictCity
  {
     public string Region { get; set; }
     public string District { get; set; }
     public string City { get; set; }
  }
}

How should be formated the name attribute of input elements for properties Region, Distirct, City in html in order to make model binder populate collection "ICollection RegionDistrictCity"?

I tried to have an action method with parameter of type "ClientInformation" and html name attributes formated like "[index].PropertyName" but in that case only the property "UserName" is binded.

I tried to have action method with parameter name "client" and have html names attributes formated like "client[index].PropertyName" but it doesn't work. (in tha case if I there is a "List client" then it would get populated)

Thanks.

1 Answer 1

11

In MVC4 you should use a for loop instead of a foreach to bind your collection. Then the model binder will be able to populate your model when you submit your data.

@for (int i = 0; i < Model.RegionDistrictCity.Count; i++)
        {
            @Html.EditorFor(model => Model.RegionDistrictCity[i].Region)
        }

But this will only work if you are not deleting or adding items to your collection dynamically. If you want to do that, you should use the BeginCollectionItem helper created by steve sanderson. http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

Sign up to request clarification or add additional context in comments.

2 Comments

This is the solution. I actually needed to create "name" attribute dinamically in jQuery but the schema required by model binding is as your reported above.
I think you meant to use the variable i in your call to EditorFor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.