Simple Dropdownlist in MVC 5 with SelectList in Model


In this post we will learn how to implement simple Dropdown list with model binding and selectlist in MVC 5.

Let’s create Model as follows

Model:

Country Model
public class Country
{
    public int SelectedCountryId { get; set; }
    public System.Web.Mvc.SelectList Countries { get; set; }
}

 

Now add a controller and add the following action method in it

Action Mehtod
public ActionResult Index1(Country model)
{
    model.Countries = this.GetCountries();
    return View(model);
}

 

GetCountries Method:

GetCountries Method
[NonAction]
private SelectList GetCountries()
{
    return new SelectList(new List<SelectListItem>{
          new SelectListItem { Selected = true, Text = "–Select Country–", Value = "0"},
          new SelectListItem { Selected = false, Text = "India", Value = "1"},
        new SelectListItem {Selected = false, Text = "USA", Value = "2"},
        new SelectListItem{ Selected = false,Text = "UK", Value = "3"},
    }, "Value", "Text", "0");
}

Now add the view and write the following code:

View:

View
@model WebApplication5.Models.Country
@{
    ViewBag.Title = "Index1";
}

<h2>Dropdownlist with SelectList and model binding</h2>

@using (Html.BeginForm())
{
    if (Model.Countries != null)
    {
        @Html.Label("County: ")
        @Html.DropDownListFor(m => m.SelectedCountryId, Model.Countries)<br />
    }
    <input type="submit" name="name" value="Submit" /><br />
    if (Model.SelectedCountryId > 0)
    {
        @Html.Label("Selected Country : ")
        @Html.Label(Model.Countries.Where(c => c.Value == Model.SelectedCountryId.ToString()).Select(c => c.Text).FirstOrDefault())
    }
}

 

Now rebuild the application 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