开发者

How to updating IEnumerable<MyObject> in mvc?

开发者 https://www.devze.com 2023-04-05 09:09 出处:网络
I have model MyObject and then in开发者_如何学C the view I have @model IEnumerable<MyProject.Models.MyObject>

I have model MyObject and then in开发者_如何学C the view I have

@model IEnumerable<MyProject.Models.MyObject>

and then further down a form :

@using(Html.BeginForm())
{
    @foreach(MyObject m in Model)
    {
        @Html.TextboxFor(x => x.Name)
    }
}

<input type="submit" value="modify" />

I am trying to get this in my controller like this:

[HttpPost]
public void Update(MyObject _myOject)
{
}

When I see the source code, all name is repeated and _myObject is not correctly populated

how do I update a list of objects and save them all at once in MVC?


You action method is waiting for a single parameter named _myObject. And you want to update list of objects

try something like this:

@using(Html.BeginForm(......))
{
    int i = 0;
    foreach(MyObject m in Model)
    {
        @Html.TextBox(string.Format("_myObjects[{0}].Name", i), m.Name)
        i++;
    }

    <input type="submit" value="modify" />
}

and your action method should look like that:

[HttpPost]
public void Update(IList<MyObject> _myObjects)
{
}

then you will be able to update this list at once

0

精彩评论

暂无评论...
验证码 换一张
取 消