Asp.net mvc modelbinding optional collections

I'm having trouble understanding how asp.net mvc model binders work.

Models

public class Detail
{
  public Guid Id { get; set; }
  public string Title {get; set; }    
}

public class Master
{
  public Guid Id { get; set;}
  public string Title { get; set; }
  public List<Detail> Details { get; set; }
}

View

 <!-- part of master view in ~/Views/Master/EditMaster.cshtml -->
 @model Master

 @using (Html.BeginForm())
 {
     @Html.HiddenFor(m => m.Id)
     @Html.TextBoxFor(m => m.Title)

     @Html.EditorFor(m => m.Details)

     <!-- snip -->
 }

 <!-- detail view in ~/Views/Master/EditorTemplates/Detail.cshtml -->
 @model Detail

 @Html.HiddenFor(m => m.Id)
 @Html.EditorFor(m => m.Title)

controller

// Alternative 1 - the one that does not work
public ActionResult Save(Master master)
{
   // master.Details not populated!
}

// Alternative 2 - one that do work
public ActionResult Save(Master master, [Bind(Prefix="Details")]IEnumerable<Detail> details)
{
   // master.Details still not populated, but details parameter is.
}

Rendered html

<form action="..." method="post">
  <input type="hidden" name="Id" value="....">
  <input type="text" name="Title" value="master title">
  <input type="hidden" name="Details[0].Id" value="....">
  <input type="text" name="Details[0].Title value="detail title">
  <input type="hidden" name="Details[1].Id" value="....">
  <input type="text" name="Details[1].Title value="detail title">
  <input type="hidden" name="Details[2].Id" value="....">
  <input type="text" name="Details[2].Title value="detail title">
  <input type="submit">
</form>

Why is it required that the mediator fill in the Details property of the model by default? Why should I include it as a separate parameter in the controller?

I read several posts about asp and list binding, including Haackeds, which are mentioned several times in other issues. It was this thread on SO that led me to the option [Binding(Prefix...)]. It says that “the model is probably too complicated,” but what exactly is “too complicated” for a standard communication device to work with?

+3
source
1

" ". (, Details) .

EditorTemplates. editorTemplate , . EditorTemplates EditorTemplates , . editortemplate . , Detail.cshtml

editortemplate - :

@model Detail

@Html.HiddenFor(m => m.Id)
@Html.TextBoxFor(m => m.Title)

, @Html.EditorFor(m => m.Details) regualar, Details .

, , . :

public ActionResult Save(Master model)
{ 

}

Save, model.Details .

, MVC , . , , , .

0

All Articles