Radiobutton List inside foreach in MVC 5 using model


In this post we will learn How to implement Radiobutton list with list in foreach loop in mvc 5 with model using html helper radiobuttonlistfor

Model:

First add models as follows

public class Country
    {
        public int CountryId { get; set; }
        public List<City> Cities { get; set; }
        public int SelectedCityId { get; set; }
        public string SelectedCityName
        {
            get
            {
                if (this.Cities != null && this.SelectedCityId > 0)
                {
                    return Cities.Where(n => n.Id == this.SelectedCityId).Select(s => s.CityName).FirstOrDefault();
                }
                else
                {
                    return string.Empty;
                }
            }
        }
    }
    public class City
    {
        public int Id { get; set; }
        public string CityName { get; set; }
    }

Controller:

Add a controller and a action method in it as follows

public ActionResult rdbtnListWithForeach(Country model)
        {
            List<City> cities = new List<City>() {
                new City(){Id = 1, CityName="Hyderabad"},
                new City(){Id = 2, CityName="Ongole"},
                new City(){Id = 3, CityName="Guntur"},
                new City(){Id = 4, CityName="Vijayawada"}
            };
            model.Cities = cities;
            return View(model);
        }

View:

@model MVCControls.Models.Country
@{
    ViewBag.Title = "Radiobutton List inside foreach in MVC 5 using model || Chikkanti.Wordpress.com";
}

<h2>Radiobutton List inside foreach in MVC 5</h2>

@using (Html.BeginForm())
{
    foreach (var city in Model.Cities)
    {
        @Html.RadioButtonFor(g => g.SelectedCityId, city.Id)@Html.Label(city.CityName)
        <br />
    }
    <br />
    <input type="submit" value="Submit" /><br />
    if (!string.IsNullOrEmpty(Model.SelectedCityName))
    {
        @Html.Label("Your selected city is: " + Model.SelectedCityName);
    }
}

Now Rebuild the application and run.

Output:

image

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