4

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?

2
  • is Model.Roles a collection of any role items? Commented Oct 19, 2011 at 21:08
  • checkout this link Commented Mar 22, 2014 at 14:14

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.