MVC- Model Binding on a Complex Type

2019-07-20 09:31发布

问题:

If I have a Model like this:

public class Search
{
    public int Id { get; set; }
    public string UserDefinedName { get; set; }
    public SearchAge Age { get; set; }
    public virtual ICollection<SearchBachelors> Bachelors { get; set; }
}

And I render the partial view for Age property dynamically using something like this:

@Ajax.ActionLink("Age", "SearchAge", new AjaxOptions { UpdateTargetId = "search-stage", InsertionMode = InsertionMode.InsertAfter })

That partial view looks like this:

@model HireWireWeb.Models.Campaign.Search.Search
<div>
    @Html.DropDownListFor(m => m.Age.MaximumAge, HireWireWeb.Models.Constants.SLIST_AGE_LIST)
    @Html.DropDownListFor(m => m.Age.MinimumAge, HireWireWeb.Models.Constants.SLIST_AGE_LIST)
</div>

(Note that I'm not passing "SearchAge" as the model here, but rather it's parent, "Search" since it's only how I can get the "SearchAge" values posted on form submit, under the rendered "Search" Form) - According to this Answer

My question is, how can I do the same thing with the partial view for "Bachelors" property, since it's an ICollection?

回答1:

MVC's standard model-binding system needs to be able to create the Types being 'bound'. It can't create an interface, so the simplest way to fix this issue is to change the type to List<SearchBachelors>. You can then have a partial view something like this:

@model HireWireWeb.Models.Campaign.Search.Search
<div>
    @for(var i = 0;i<Model.Bachelors.Count;++i)
    {
        @Html.TextBoxFor(m => m.Bachelors[i].Name)
    }
</div>

...the rendered output will be named in such a way as to be bound into your List property using the indexes of the elements in the list when you submit the form.