【问题标题】:ASP.NET MVC 3 - How to populate list of radio buttons from databaseASP.NET MVC 3 - 如何从数据库中填充单选按钮列表
【发布时间】:2011-10-19 20:55:38
【问题描述】:

在 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>

这很好用,但这需要我对值进行硬编码。现在我只有两个值,但它可能会根据我的数据库中的数据而改变。如何从数据库中动态填充此单选按钮列表?谢谢


我的控制器中有一个注册 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 列表。然后我将如何在我的模型中访问此列表?

【问题讨论】:

  • Model.Roles 是任何角色项的集合吗?
  • 签出此link

标签: c# asp.net asp.net-mvc-3


【解决方案1】:

在您的控制器中,您需要从数据库中获取值并将它们放入您的模型或视图包中。

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>

(我没有编译/测试它,但您应该能够修复/调整它以满足您的需求。)

【讨论】:

  • 我的控制器中有一个注册 ActionResult 方法,如下所示:
猜你喜欢
  • 2012-05-26
  • 1970-01-01
  • 2012-05-12
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多