ASP.NET MVC 3 -如何从数据库填充单选按钮列表
本文关键字:数据库 填充 单选按钮 列表 NET MVC ASP | 更新日期: 2023-09-27 18:11:40
在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。模型有一个AdminRoles列表。那么我该如何在模型中访问这个列表呢?
在您的控制器中,您需要从数据库中获取值并将它们放入模型或viewbag中。
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>
(我没有编译/测试它,但是您应该能够修复/调整它以满足您的需要。)