gpt4 book ai didi

asp.net-mvc - 将复选框值绑定(bind)到模型 mvc 中的列表

转载 作者:行者123 更新时间:2023-12-04 22:14:19 24 4
gpt4 key购买 nike

我的问题是我必须创建如下布局,使用 MVC 为用户分配权限。 Sample of the lay out needed

现在创建复选框没有问题,我将使用用户列表创建它。
但是在提交表格时,我应该将其提交到下面的列表中。

public class UserRightsViewModel
{
public UserRightsViewModel()
{
_screenrights = new List<ScreenRight>();

}
public String Id { get; set; }// Role Name
List<ScreenRight> _screenrights;
public List<ScreenRight> ScreenRights { get { return _screenrights; } set { _screenrights = value; } }

}

screenRight 的定义如下
public class ScreenRight
{
public String UserName { get; set; }
public Boolean Select{ get; set; }
public Boolean Add{ get; set; }
public Boolean Edit{ get; set; }
,,,
}

现在,在提交表单时,我如何以正确的格式将其发布到 Controller 。

最佳答案

Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
var model = new UserRightsViewModel
{
// Obviously those could come from some data source
ScreenRights = new[]
{
new ScreenRight { UserName = "Robert", Select = true, Add = false, Edit = false },
new ScreenRight { UserName = "John", Select = true, Add = true, Edit = false },
new ScreenRight { UserName = "Mike", Select = true, Add = true, Edit = false },
new ScreenRight { UserName = "Allan", Select = true, Add = true, Edit = true },
new ScreenRight { UserName = "Richard", Select = false, Add = false, Edit = false },
}.ToList()
};
return View(model);
}

[HttpPost]
public ActionResult Index(UserRightsViewModel model)
{
// The view model will be correctly populated here
// TODO: do some processing with them and redirect or
// render the same view passing it the view model
...
}
}

看法:
@model UserRightsViewModel

@using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>User Id</th>
<th>Select</th>
<th>Add</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.ScreenRights.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(x => x.ScreenRights[i].UserName)
@Html.HiddenFor(x => x.ScreenRights[i].UserName)
</td>
<td>
@Html.CheckBoxFor(x => x.ScreenRights[i].Select)
</td>
<td>
@Html.CheckBoxFor(x => x.ScreenRights[i].Add)
</td>
<td>
@Html.CheckBoxFor(x => x.ScreenRights[i].Edit)
</td>
</tr>
}
</tbody>
</table>

<button type="submit">OK</button>
}

进一步阅读: Model Binding To a List .

关于asp.net-mvc - 将复选框值绑定(bind)到模型 mvc 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13765741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com