在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>
哪个工作正常,但这需要我对值进行硬编码。现在我只有两个值,但它可能会根据我的数据库中的数据而改变。我怎么能从数据库动态填充这个radiobuttons列表?感谢
我的控制器中有一个注册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列表。那么我如何在我的模型中访问此列表?
答案 0 :(得分:3)
在您的控制器中,您需要从数据库中获取值并将它们放入模型或视图包中。
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>
(我没有编译/测试它,但您应该能够修复/调整它以满足您的需求。)