Reputation: 24606
This one seems painfully obvious to me, but for some reason I can't get it working the way I want it to. Perhaps it isn't possible the way I am doing it, but that seems unlikely. This question may be somewhat related: ASP.NET MVC Model Binding Related Entities on Same Page.
I have an EditorTemplate to edit an entity with multiple related entity references. When the editor is rendered the user is given a drop down list to select related entities from, with the drop down list returning an ID as its value.
<%=Html.DropDownListFor(m => m.Entity.ID, ...)%>
When the request is sent the form value is named as expected: "Entity.ID", however my strongly typed Model defined as an action parameter doesn't have Entity.ID populated with the value passed in the request.
public ActionResult AddEntity(EntityWithChildEntities entityWithChildEntities) { }
I tried fiddling around with the Bind() attribute and specified Bind(Include = "Entity.ID")
on the entityWithChildEntities, but that doesn't seem to work. I also tried Bind(Include = "Entity")
, but that resulted in the ModelBinder attempting to bind a full "Entity" definition (not surprisingly).
Is there any way to get the default model binder to fill the child entity ID or will I need to add action parameters for each child entity's ID and then manually copy the values into the model definition?
Upvotes: 0
Views: 1491
Reputation: 1038730
There's no DropDownListFor
helper method that takes one parameter. The standard DropDownListFor method takes at least two parameters: the first is a lambda used to calculate the name of the select and the second is an IEnumerable<SelectListItem>
:
<%= Html.DropDownListFor(m => m.Entity.ID, Model.EntitiesList) %>
Also how does the EntityWithChildEntities
type looks like? It must be something like this:
public class EntityType
{
public string ID { get; set; }
}
public class EntityWithChildEntities
{
public EntityType Entity { get; set; }
public IEnumerable<SelectListItem> EntitiesList
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "foo" },
new SelectListItem { Value = "2", Text = "bar" },
}
}
}
}
Upvotes: 0
Reputation: 22760
Have you looked at AutoMapper? I agree that this shouldn't be required because the binding should work but...
I've had a little difficulty with using the Html.XYZFor
helper and have reverted back to using the MVC 1.1 notation and it all works.
Upvotes: 1