Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...