ASP.NET MVC 3-如何从数据库填充单选按钮列表 [英] ASP.NET MVC 3 - How to populate list of radio buttons from database

查看:97
本文介绍了ASP.NET MVC 3-如何从数据库填充单选按钮列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Asp.net MVC 3中,我的单选按钮设置如下:

In Asp.net MVC 3, I have my radio buttons set up like this:

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

哪个工作正常,但这需要我对值进行硬编码.现在,我只有两个值,但是可以根据数据库中的数据进行更改.如何从数据库动态填充此单选按钮列表?谢谢

Which works fine, but this requires me to hardcode the values. Right now I only have two values, but it could change based on data in my db. How could I populate this list of radiobuttons dynamically from the database? Thanks

我的控制器中有一个Register ActionResult方法,如下所示:

I have a Register ActionResult method in my Controller like this:

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列表.然后我将如何在模型中访问此列表?

So the ViewData.Model has a list of AdminRoles. How would I then access this list in my model?

推荐答案

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

In your controller you will need to get the values from the database and put them in your model or the viewbag.

ViewBag.RadioButtonValues = db.Roles.Select(r => r.RoleDescription).ToList();

然后在您的视图中,您只需要使用循环将它们吐出即可:

Then in your view you just use a loop to spit them out:

@{
    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>

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

(I did not get to compile / test this, but you should be able to fix / tweak it to fit your needs.)

这篇关于ASP.NET MVC 3-如何从数据库填充单选按钮列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆