Manually binding complex model array to controller action

萝らか妹 提交于 2019-12-13 08:08:33

问题


For some reason I'm trying to manually bind an array of a Complex Model but I'm getting a null reference exception in my controller, the binder doesn't retrieve the parameter. I've found this question which is very similar (the only difference is actually the type of the model) but I don't understand why it doesn't work in my case.

Here is what I have.

In my controller

public ActionResult MyAction(ComplexType[] models)
{
    foreach(ComplexType c in models) // Exception at this point, the parameter is null
    {
        //Do stuff
    }
}

In my View :

    @using(Html.BeginForm("MyAction","Controller"))
    {
        @Html.AntiForgeryToken()
<table>
        @for (int i = 0; i < Model._MyProperty.Count; i++ )
        {
            var d = Model._MyProperty[i];
            @:<tr>
                @:<td> @Html.CheckBox("models.Property1["+i+"]", d.Property1) 
                    @Html.Hidden("models.ID["+i+"]",d.ID)
                    @Html.Hidden("models.Property2["+i+"]")
                    @Html.Hidden("models.Property3["+i+"]")
                    @Html.Hidden("models.Property4["+i+"]")
                @:  </td>
            @:</tr>
        }

 //Submit Button
 </table>

}

And here is my class :

class ComplexType
{
    int ID {get;set;}
    int Property1{get;set;}
    int Property2{get;set;}
    int Property3{get;set;}
    int Property4{get;set;}
}

I've tried to change ComplexType[] to ICollection in the controller but it didn't work. Also, just for info, my ViewModel is not the Model i'm tying to bing. I need to have several forms working on different datatypes in this single view.


回答1:


You are naming your elements in the loop as follows

<input type="hidden" name="models.Property2[0]" value
<input type="hidden" name="models.Property2[1]" value

when it should be

<input type="hidden" name="models[0].Property2" value
<input type="hidden" name="models[1].Property2" value


来源:https://stackoverflow.com/questions/24250135/manually-binding-complex-model-array-to-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!