ASP.NET MVC 3 - How to populate list of radio butt

2019-04-10 01:19发布

问题:

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


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();
        }

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

回答1:

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