开发者

Why DefaultModelBinder in MVC3 does not Bind?

I do not understand why the DefaultModelBinder in MVC3 does not map t开发者_StackOverflow中文版he Form Post Data to my action method. I have the following ViewModels:

public class DisplayExcelTableViewModel
{
   public string UploadedFileName { get; set; }
   public List<string> TableHeaders { get; set; }
   public List<TableRowViewModel> TableRows { get; set; }
}

public class TableRowViewModel
{
   public List<string> TableColumns { get; set; }
}

They are displayed in a (partial) View using DisplayTemplates:

@using (Html.BeginForm("SubmitExcel", "Home", FormMethod.Post))
{ 
<fieldset>

<table>
<tr>
<th>@Html.DisplayFor(m => m.TableHeaders)</th>//<input id="TableHeaders_0_" name="TableHeaders[0]" type="text" value="Opportunity Id" />
</tr>

<tr>
<td>@Html.DisplayFor(m => m.TableRows)</td>//<input id="TableRows_0__TableColumns_0_" name="TableRows[0].TableColumns[0]" type="text" value="1-H7PKD9" />
</tr>

</table>           


<input type="submit" value="Send" />
</fieldset> 
}

And the action method looks like this:

public ActionResult SubmitExcel(DisplayExcelTableViewModel excelTable)

To try whether it worked just with one TableRows I tried:

public ActionResult SubmitExcel([Bind(Prefix = "TableRows")] TableRowViewModel TableRows)

to test I also tried to put List<TableRows> and take out the Bind attribute. It does not work. I got a runtime exception:

"System.MissingMethodException: No parameterless constructor defined for this object."

May you tell me what I am doing wrong?

Thanks Francesco


The problem is that my ViewModels DID NOT have a parameterless constructor, which is what the Default Model Binder looks for(uses .NET’s Activator.CreateInstance() method, which relies on those types having public parameterless constructors).The solutions in this case are two:

1) Add a parameterless constructor to the ViewModel and the other custom classes wrapped inside it.

2) Create a custom model binder that covers also the case of your ViewModel

Thanks

Source: Pro ASP.NET MVC2 Framework (2nd Edition)


Have you checked (for example with Firebug) whether are form values being posted to the server? I'm asking because Html.DisplayFor usually renders display elements, whereas for posting values you usually have to use Html.EditorFor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜