手动将复杂模型数组绑定到控制器动作 [英] Manually binding complex model array to controller action

查看:138
本文介绍了手动将复杂模型数组绑定到控制器动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我试图手动绑定复杂模型的数组,但是在控制器中收到空引用异常,绑定器无法检索该参数.我发现了这个问题,它非常相似(唯一的区别实际上是类型的模型),但我不明白为什么在我的情况下它不起作用.

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.

这就是我所拥有的.

在我的控制器中

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

在我看来:

    @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>

}

这是我的课:

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

我试图在控制器中将ComplexType []更改为ICollection,但是没有用.另外,仅出于信息目的,我的ViewModel不是我要绑定的Model.我需要在单个视图中使用几种形式处理不同的数据类型.

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.

推荐答案

您正在按如下所示在循环中命名元素

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

应该在什么时候

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

这篇关于手动将复杂模型数组绑定到控制器动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆