ASP.NET MVC Model list binding

2019-04-06 22:27发布

问题:

Here is my model:

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

Controller:

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);
    }

View (Index):

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

I delete second pair:

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

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?

回答1:

This may be helpful to you....

need to place Hidden field on each item...

MVC3 Non-Sequential Indices and DefaultModelBinder



回答2:

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