ASP.NET MVC 模型列表绑定

2024-04-23

这是我的模型:

public class Items
    {
        public string Foo { get; set; }
        public string Bar { get; set; }
    }

控制器:

public ActionResult Index()
    {
        var model = new List<Items>
                        {
                            new Items
                                {
                                    Foo = "foo",
                                    Bar = "bar"
                                },
                            new Items
                                {
                                    Foo = "ai",
                                    Bar = "ia"
                                },
                            new Items
                                {
                                    Foo = "one",
                                    Bar = "two"
                                }
                        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(List<Items> model)
    {
        return View(model);
    }

查看(索引):

@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++)
    {
        <div onclick="$(this).remove();">
            @Html.TextBoxFor(model => model[i].Foo) <br/>
            @Html.TextBoxFor(model => model[i].Bar)
        </div>
    }
    <div>
        <input type="submit"/>
    </div>
}

我删除第二对:

    <div onclick="$(this).remove();">
        <input name="[0].Foo" type="text" value="foo"> <br>
        <input name="[0].Bar" type="text" value="bar">
    </div>

    <div onclick="$(this).remove();">
        <input name="[2].Foo" type="text" value="one"> <br>
        <input name="[2].Bar" type="text" value="two">
    </div>

发帖时,我只得到第一对(“foo”和“bar”)。这是因为第三对的索引为“2”。我想获得这两对(不使用 FormCollection。我希望它自动绑定)。实际上,我在表单上还有许多其他输入,因此我不想重新加载索引并将索引重新附加到每个输入。你能帮助我吗?


这可能对你有帮助......

需要在每个项目上放置隐藏字段...

MVC3 非顺序索引和 DefaultModelBinder https://stackoverflow.com/questions/8598214/mvc3-non-sequential-indices-and-defaultmodelbinder

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET MVC 模型列表绑定 的相关文章