DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Generating a radiobuttonlist control in mvc using HTML helpers

In MVC, you can generate a RadioButtonList control using HTML helpers. However, please note that MVC does not have a built-in RadioButtonList control like Web Forms. You can achieve the same functionality by using a combination of HTML helpers and loops. Here's an example:

Let's assume you have a model called RadioButtonListModel with properties for the list items and the selected value:

public class RadioButtonListModel
{
    public List<SelectListItem> Items { get; set; }
    public string SelectedValue { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

In your controller action, you can populate the Items property with the options for your radio button list and pass the model to the view:

public ActionResult Index()
{
    var model = new RadioButtonListModel
    {
        Items = new List<SelectListItem>
        {
            new SelectListItem { Value = "option1", Text = "Option 1" },
            new SelectListItem { Value = "option2", Text = "Option 2" },
            new SelectListItem { Value = "option3", Text = "Option 3" }
        }
    };

    return View(model);
}
Enter fullscreen mode Exit fullscreen mode

In your view, you can generate the radio button list using a for loop and the Html.RadioButton helper method:

@model RadioButtonListModel

@for (int i = 0; i < Model.Items.Count; i++)
{
    <div>
        @Html.RadioButtonFor(m => m.SelectedValue, Model.Items[i].Value)
        @Html.LabelFor(m => m.SelectedValue, Model.Items[i].Text)
    </div>
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we're iterating over the Items list and generating a radio button and label for each item. The RadioButtonFor helper generates the radio button, and the LabelFor helper generates the label associated with the radio button. The RadioButtonFor helper uses the SelectedValue property of the model to determine the selected radio button.

Make sure to include the necessary namespaces in your view or add them in the Web.config file:

@using System.Web.Mvc
@using System.Web.Mvc.Html
Enter fullscreen mode Exit fullscreen mode

This way, when you navigate to the corresponding action in your MVC application, you should see a radio button list with the options you specified in the controller.

Top comments (0)