的CheckBoxList多重选择:难度模型绑定回 [英] CheckBoxList multiple selections: difficulty in model bind back
本文介绍了的CheckBoxList多重选择:难度模型绑定回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类如下:
public class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
和公共UserRoleModel [] {的UserRole获取;组; }
我的控制器如下:
public ActionResult CreateUser()
{
UserDetailsModel model = new UserDetailsModel();
return View(model);
}
[HttpPost]
public ActionResult CreateUser(UserDetailsModel model)
{
return View(model);
}
在我看来,我有
In my view I am having
>@foreach (var item in Model.UserRoles)
{
name = "UserRoles"+ ".Value["+ i + "]";
id= "UserRoles" + "_Value[" + i++ + "]";
selected = item.UserRole ? "checked=\"checked\"" : "";
<p>
<input type="checkbox" name="@name" id="@id" @selected value="true" />
<label for="@id">@item.Role</label>
<input type="hidden" name="@name" value="false" />
</p>
}
尽管被我认为相应的显示值,没有模型绑定回的UserRole。我在想什么或者有没有更好的和更清洁的方法是什么?
Despite the values being displayed accordingly in my view, there is no model bind back for UserRoles. What am I missing or is there any better and cleaner method?
推荐答案
这种事情是很好用的编辑模板来实现的。他们还避免你从你的看法写面条code。例如:
Those kind of things are nicely achieved with editor templates. They also avoid you from writing spaghetti code in your views. Example:
型号:
public class UserDetailsModel
{
public IEnumerable<UserRoleModel> Roles { get; set; }
}
public class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new UserDetailsModel
{
// Fill with some dummy stuff
Roles = Enumerable.Range(1, 5).Select(x => new UserRoleModel
{
Role = "role " + x,
UserRole = false
})
});
}
[HttpPost]
public ActionResult Index(UserDetailsModel model)
{
return View(model);
}
}
查看(〜/查看/主页/ Index.cshtml
)
@model AppName.Models.UserDetailsModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Roles)
<input type="submit" value="OK" />
}
编辑模板(〜/查看/主页/ EditorTemplates / UserRoleModel.cshtml
)
@model AppName.Models.UserRoleModel
@Html.CheckBoxFor(x => x.UserRole)
@Html.LabelFor(x => x.Role, Model.Role)
@Html.HiddenFor(x => x.Role)
现在这就是我所说的清洁材料。
Now that's what I call clean stuff.
这篇关于的CheckBoxList多重选择:难度模型绑定回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文