Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

asp.net mvc - Manually binding complex model array to controller action

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...