Menu

Dropdown Binding in MVC

Hello Friend,

Here we have gave demo for dropdown binding in MVC.

Download Source code:=>DropDownBindingInMVC.rar

1. Create Model For assign dropdown value in View.

public class ModelCountry
{
public ModelCountry()
{
lstCountryList.Add(new SelectListItem { Text = "Select", Value = "-1" });
lstCountryList.Add(new SelectListItem { Text = "India", Value = "1" });
lstCountryList.Add(new SelectListItem { Text = "Pak", Value = "2" });
lstCountryList.Add(new SelectListItem { Text = "US", Value = "3" });
lstCountryList.Add(new SelectListItem { Text = "UK", Value = "4" });
}
#region Property
public int CountryId { get; set; }
public IList lstCountryList = new List();
#endregion
}

2.Controller pass model to view .

public class CountryController : Controller
{
//
// GET: /Country/

public ActionResult Index()
{
ModelCountry objCountry = new ModelCountry();
return View(objCountry);
}
}

3. View Code Look Like below

@model DropDownBindingInMVC.Models.ModelCountry
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Dropdown Binding</h2>
<div>Using <b>DropDownListFor</b>Country List : @Html.DropDownListFor(m => m.CountryId, Model.lstCountryList)

</div>
&amp;nbsp;
<div>Using <b>DropDownList</b>Country List : @Html.DropDownList("CountryId", Model.lstCountryList)

</div>

You can get Selected dropdown value using Model.CountryId

4. Final Out put
Dropdownbinding

Thanks,
Please share it.

No comments

Leave a Reply


6 + = 9

Categories