Jiju John
Jiju John

Reputation: 821

bulk update in mvc

I want to update the list of users, In my controller I have returned the list of users

return View("usersList", user);

and In view I use

@using (Html.BeginForm("usersList", "UserManagement"))
{
    @Html.EditorFor(model => model, "tbl_UserList");
}

and in editor template I use 'tbl_UserList.cshtml' as below

@model IList<tbl_Users>

@using (Html.BeginForm())
{
<table>
    <tr>
    <th>
        @Html.DisplayNameFor(model => model[0].FirstName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model[0].LastName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model[0].Email)
    </th>

    </tr>

@foreach (var item in Model) {
    <tr>
    <td>
        @Html.EditorFor(modelitem => item.FirstName)
    </td>
    <td>
        @Html.EditorFor(modelItem => item.LastName)
    </td>
    <td>
        @Html.EditorFor(modelItem => item.Email)
    </td>
    </tr>
}

</table>

<input id="subButton" type="submit" value="submit" title="submit data" />
}

and in controller

[HttpPost]
public ActionResult UserList(List<tbl_Users> users)
{
    //..
}

here the users in controller is null, how can I solve this> thanks

Upvotes: 3

Views: 1612

Answers (1)

user3559349
user3559349

Reputation:

Change your EditorTemplate to

@model tbl_Users
<tr>
  <td>@Html.EditorFor(m => m.FirstName)</td>
  <td>@Html.EditorFor(m => m.LastName)</td>
  <td>@Html.EditorFor(m => m.Email)</td>
</tr>

and rename it to tbl_Users.cshtml

Then in the main view

@model IList<tbl_Users>
@using (Html.BeginForm("usersList", "UserManagement"))
{
  <table>
    <thead>
      <tr>
        <td>@Html.DisplayNameFor(m => m.FirstName)</td>
        ....
      </tr>
    </thead>
    <tbody>
      @Html.EditorFor(m => m); // do not specify a name
    </tbody>
  </table>
}

Note that you current foreach loop is generating duplicate id attributes (invalid html) and duplicate name attributes which will not bind to a collection (inspect the html before and after to understand).

Upvotes: 2

Related Questions