ASP.NET MVC 3 - How to populate a list of radio buttons from a database

In Asp.net MVC 3, I have my switches configured as follows:

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

This works fine, but for this I need to hardcode the values. Right now, I have only two values, but that can change based on the data in my db. How can I dynamically populate this list of radio objects from a database? Thanks


I have a Register ActionResult method in my controller, for example:

 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 ViewData.Model has a list of AdminRoles. How could I access this list in my model?

+4
source share
1 answer

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

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

Then, in your opinion, 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 could not compile / verify this, but you should be able to fix / tune it according to your needs.)

+3
source

All Articles