Search code examples
razormodel-view-controllerradio-buttonradiobuttonlist

MVC Radio Button List Grid


I've got an issue trying to read the selected values from the radio button list in my [HttpPost] Controller. Any help would be greatly appreciated.

Sample View

My models are the following:

public partial class RoleModel
{
    public Guid RoleId { get; set; }

    public string Description { get; set; }

    public List<RoleModuleAccessRight> RoleModuleAccessRights { get; set; }
}

public class RoleModuleAccessRight
{
    public string ModuleName { get; set; }
    public int ModuleId { get; set; }
    public bool HasFullControl { get; set; }
    public bool HasReadOnly { get; set; }
    public bool HasNoAccess { get; set; }
}

My Controllers:

[HttpGet]
public ActionResult Edit(Guid id)
    {
        RoleModel role = BusinessLayer.UserManager.GetRoleModel(id);

        role.RoleModuleAccessRights = BusinessLayer.UserManager.GetModulesForRoleId(role.RoleId);
        return PartialView("_Edit", role);
    }

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(RoleModel model)
    {
        if (ModelState.IsValid)
        {
            BusinessLayer.UserManager.UpdateAccessRights(model);
            string url = Url.Action("List", "Roles");
            return Json(new { success = true, url = url });
        }
        return PartialView("_Edit", model);
    }

My View code:

@foreach (RoleModuleAccessRight item in Model.RoleModuleAccessRights)
            {
                @Html.HiddenFor(model => item.ModuleId)
                string radioName = string.Format("RoleModuleAccessRights_{0}", item.ModuleId.ToString());
                <tr>
                    <td>@item.ModuleName</td>
                    <td>
                        <div class="checkbox">
                            @Html.RadioButton(radioName, item.HasFullControl, item.HasFullControl)
                        </div>
                    </td>
                    <td>
                        <div class="checkbox">
                            @Html.RadioButton(radioName, item.HasReadOnly, item.HasReadOnly)
                        </div>
                    </td>
                    <td>
                        <div class="checkbox">
                            @Html.RadioButton(radioName, item.HasNoAccess, item.HasNoAccess)
                        </div>
                    </td>
                </tr>
            }

The issue im having is that when i post the form im not able to grab the information in my [HttpPost] Controller. It returns "null" enter image description here

The mark up generated is the following: enter image description here


Solution

  • Looking at your code, your ids are not unique which is going to break things, also using a dedicated template will simplify your problem. See this example https://stackoverflow.com/a/7668325

    Another more generic article: Multiple radio button groups in MVC 4 Razor