ASP.NET MVC模型绑定列表 [英] ASP.NET MVC Model list binding

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

问题描述

下面是我的模型:

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和酒吧)。这是因为第三对具有指数2。我想获得两对(不使用的FormCollection。我希望它自动绑定)。在现实中,我有很多形式的其他投入,所以我不想重装并重新索引每个输入。你能帮助我吗?

When posting, i get only first pair ("foo" and "bar"). It's because third pair has index "2". I want to get both pairs(Not using FormCollection. I want it to bind automatically). In reality, I have many other inputs on form, so i don't want to reload and reattach indices to each input. Can you help me?

推荐答案

我找到了解决方案,这要归功于艾米特生主:

I found solution, thanks to Amit Prajapati:

@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++)
    {
        var identifier = Guid.NewGuid();
        <div onclick="$(this).remove();">
            @Html.Hidden("Index", identifier)
            @Html.TextBox("[" + identifier + "].Foo")
            <br/>
            @Html.TextBox("[" + identifier + "].Bar")
        </div>
    }
    <div>
        <input type="submit" />
    </div>
}

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

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