模型绑定泛型列表在asp.net mvc的空 [英] Model binding generic list is null in asp.net mvc

查看:117
本文介绍了模型绑定泛型列表在asp.net mvc的空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在剃刀的foreach中的index.html绑定对象:

I am binding objects in a razor foreach in the index.html:

查看

@using (Ajax.BeginForm("Save", "Unit", new AjaxOptions { OnSuccess = "onSuccess" }))
    {

<button type="submit" class="btn btn-default" id="saveUnits"><i class="fa fa-save"></i></button>


    <table>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>

                    @Html.HiddenFor(modelItem => item.UnitId)
                    <td>
                        @Html.EditorFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.ErrorText)
                    </td>

                </tr>
            }
        </tbody>
    </table>
}

我已经抓住发送到提琴手我的操作参数的数据,并得到这个:

I have grabbed the data sent to my action parameter with fiddler and got this:

item.UnitId=5&
item.Name=111111111111&
item.ErrorText=fsdddddddddddddddd+&

item.UnitId=5&
item.Name=+&
item.ErrorText=dddddd+&

ACTION

public ActionResult Save(List<Unit> units )
{
    return new EmptyResult();   
}

视图模型

public class Unit
{
    [HiddenInput(DisplayValue = false)]
    public int UnitId { get; set; }

    [DataType(DataType.MultilineText)]
    public string Name { get; set; }

    [DataType(DataType.MultilineText)]
    public string ErrorText { get; set; 
}

为什么我的单位例如空?该属性匹配,所以他们应该绑定!

Why is my units instance null? The properties match so they should be bound!

难道我忽略的东西吗?

推荐答案

您需要使用循环不是的foreach 循环。此外,这将是更好地使你的模型类有一个属性,它是一个集合。

You need to use a for loop not a foreach loop. Also, it would be better to make your Model class have a property which is a collection.

您模型可以是这样的:

public class UnitsViewModel
{
    public List<Unit> Units { get; set; }

    public class Unit
    {
        [HiddenInput(DisplayValue = false)]
        public int UnitId { get; set; }

        [DataType(DataType.MultilineText)]
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        public string ErrorText { get; set; }
    }
}

和你可以做你的CSHTML以下内容:

And you could do the following in your cshtml:

@for (int i = 0; i < Model.Count; i++)
{
    <tr>

        @Html.HiddenFor(m => m.Units[i].UnitId)
        <td>
            @Html.EditorFor(m => m.Units[i].Name)
        </td>
        <td>
            @Html.EditorFor(m => m.Units[i].ErrorText)
        </td>

    </tr>
}

这篇关于模型绑定泛型列表在asp.net mvc的空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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