mut*_*y91 7 c# asp.net-mvc razor asp.net-mvc-5
我有一个与用户关联的项目列表.这是一对多的关系.我希望将整个项目列表传递到视图中,以便他们可以从尚未与之关联的项目中进行选择(并且还可以查看已经关联的项目).我想从这些创建复选框.然后我想将所选择的那些发送回控制器以进行关联.我如何传递所有这些列表,包括那些尚未关联的列表,并可靠地将它们传回以进行关联?
这是我首先尝试的,但很明显这不会起作用,因为我基于通过AllItems集合传入的项目的输入,该集合与用户本身的项目没有任何关联.
<div id="item-list">
@foreach (var item in Model.AllItems)
{
<div class="ui field">
<div class="ui toggle checkbox">
<input type="checkbox" id="item-@item.ItemID" name="Items" value="@item.Active" />
<label for="item-@item.ItemID">@item.ItemName</label>
</div>
</div>
}
</div>
Run Code Online (Sandbox Code Playgroud)
小智 21
您无法使用foreach循环绑定到集合.你也不应该手动生成你的html,在这种情况下不会有效,因为未选中的复选框不会回发.始终使用强类型的html帮助程序,以便获得正确的双向模型绑定.
您尚未指出您的模型,但假设您有User并且想要Roles为该用户选择,则创建视图模型以表示您要在视图中显示的内容
public class RoleVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class UserVM
{
public UserVM()
{
Roles = new List<RoleVM>();
}
public int ID { get; set; }
public string Name { get; set; }
public List<RoleVM> Roles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在GET方法中
public ActionResult Edit(int ID)
{
UserVM model = new UserVM();
// Get you User based on the ID and map properties to the view model
// including populating the Roles and setting their IsSelect property
// based on existing roles
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
视图
@model UserVM
@using(Html.BeginForm())
{
@Html.HiddenFor(m => m.ID)
@Html.DisplayFor(m => m.Name)
for(int i = 0; i < Model.Roles.Count; i++)
{
@Html.HiddenFor(m => m.Roles[i].ID)
@Html.CheckBoxFor(m => m.Roles[i].IsSelected)
@Html.LabelFor(m => m.Roles[i].IsSelected, Model.Roles[i].Name)
}
<input type"submit" />
}
Run Code Online (Sandbox Code Playgroud)
然后在post方法中,您的模型将被绑定,您可以检查已选择的角色
[HttpPost]
public ActionResult Edit(UserVM model)
{
// Loop through model.Roles and check the IsSelected property
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7939 次 |
| 最近记录: |