Radiobutton list with enum and model in MVC 5


In this post we will learn how to implement Radiobutton list control with enum in mvc 5

Let’s sart by creating Enum for favourite subjects

Enum:

public enum FavouriteSubject
    {
        CSharp = 0,
        Aspnet = 1,
        SqlServer = 2,
        Sharepoint = 3
    }

next prepare model as follows

Model:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public FavouriteSubject FavSubject { get; set; }
    }

 

Controller:

lets create action method in controller as follows.

public ActionResult rdbtnListWithEnum(Student model)
        {
            return View(model);
        }

 

View:

We can implement view in different ways

Method 1: Radiobutton list with foreach loop

@model MVCControls.Models.Student
@using MVCControls.Models;
@{
    ViewBag.Title = "Radio Button List with enum and model || Chikkanti.Wordpress.com";
}

<h2>Radiobutton list with enum and model</h2>

@using (Html.BeginForm())
{
    foreach (var favsub in Enum.GetValues(typeof(FavouriteSubject)))
    {
        var id = TagBuilder.CreateSanitizedId(string.Format("{0}_{1}_{2}", "rdbtn", typeof(FavouriteSubject), favsub));
        <div>
            @Html.RadioButtonFor(s => s.FavSubject, favsub, new { id })
            @Html.Label(favsub.ToString(), new { @for = id })
        </div>
    }
    <input type="submit" name="name" value="Submit" />
    <br />
    @Html.Label("Your selected option: " + Model.FavSubject)
}

Method 2: Simple Radiobutton list

@model MVCControls.Models.Student
@using MVCControls.Models;
@{
    ViewBag.Title = "Radio Button List with enum and model || Chikkanti.Wordpress.com";
}

<h2>Radiobutton list with enum and model</h2>

@using (Html.BeginForm())
{
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.CSharp)@Html.Label("CSharp")<br />
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.Aspnet)@Html.Label("Aspnet")<br />
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.SqlServer)@Html.Label("SqlServer")<br />
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.Sharepoint)@Html.Label("Sharepoint")<br />
    <input type="submit" name="name" value="Submit" />
    <br />
    @Html.Label("Your selected option: " + Model.FavSubject)
}

Now rebuild the project and run

image

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s