代码改变世界

mvc post list到后台

2020-07-27 11:59  若藜520  阅读(238)  评论(0编辑  收藏  举报
@model IEnumerable<mvctest.Models.SysUser>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm())
{
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(n => n.UserName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Password)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Phone)
            </th>
            <th></th>
        </tr>

        @{
            var list = Model.ToList();
            for (int i = 0; i < list.Count; i++)
            {

                <tr>
                    <td>
                        @Html.EditorFor(modelItem => list[i].UserName, new { htmlAttributes = new { @class = "form-control" } })
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => list[i].Email, new { htmlAttributes = new { @class = "form-control" } })
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => list[i].Password, new { htmlAttributes = new { @class = "form-control" } })
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => list[i].Phone, new { htmlAttributes = new { @class = "form-control" } })
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id = list[i].ID }) |
                        @Html.ActionLink("Details", "Details", new { id = list[i].ID }) |
                        @Html.ActionLink("Delete", "Delete", new { id = list[i].ID })
                    </td>
                </tr>
            }   
        }

    </table>
    <input type="submit" value="提交" />
}
        [HttpPost]
        public ActionResult Index(List<mvctest.Models.SysUser> list)
        {
            return View(db.SysUsers.ToList());
        }

注意Action参数名称与view中的list名称一致才可以,这里view中Name属性使用了list[0].username这样的名称,即view中list的名称为list,所以Action参数也要命名为list

参考https://blog.csdn.net/jacksover/article/details/8163249