在 Asp.net MVC 3 中,我的单选按钮设置如下:
<div class="editor-label">
@Html.LabelFor(m => m.Roles)
</div>
<div class="editor-field">
@Html.RadioButtonFor(model => model.Roles,false) SuperAdmin
@Html.RadioButtonFor(model => model.Roles,false) Admin
@Html.ValidationMessageFor(model =>model.Roles)<br/>
</div>
效果很好,但这需要我对这些值进行硬编码。现在我只有两个值,但它可能会根据我的数据库中的数据而改变。我如何从数据库动态填充这个单选按钮列表?谢谢
我的控制器中有一个 Register ActionResult 方法,如下所示:
public ActionResult Register()
{
// On load, query AdminRoles table and load all admin roles into the collection based on the
// the query which just does an order by
AdminRolesQuery arq = new AdminRolesQuery();
AdminRolesCollection myAdminRolesColl = new AdminRolesCollection();
arq.OrderBy(arq.RoleName, EntitySpaces.DynamicQuery.esOrderByDirection.Ascending);
myAdminRolesColl.Load(arq);
// Store The list of AdminRoles in the ViewBag
//ViewBag.RadioAdminRoles = myAdminRolesColl.Select(r => r.RoleName).ToList();
ViewData.Model = myAdminRolesColl.Select(r => r.RoleName).ToList();
return View();
}
因此 ViewData.Model 有一个 AdminRoles 列表。然后我将如何在我的模型中访问此列表?
在控制器中,您需要从数据库获取值并将它们放入模型或视图包中。
ViewBag.RadioButtonValues = db.Roles.Select(r => r.RoleDescription).ToList();
然后在你看来你只需使用一个循环将它们吐出来:
@{
List<String> rbValues = (List<String>)ViewBag.RadioButtonValues;
}
<div class="editor-field">
@foreach (String val in rbValues) {
@Html.RadioButtonFor(model => model.Roles,false) @val
}
@Html.ValidationMessageFor(model =>model.Roles)<br/>
</div>
(我没有编译/测试这个,但你应该能够修复/调整它以满足你的需要。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)