In this demo we are binding a Country Name Column with Razor Dropdown.
1- first Create a Country TAble named Country.
3- Add a Model Class named CountryModel.cs. below are the Code specified....
1- first Create a Country TAble named Country.
Create Table Country
(
CountryID int not null,
CountryName varchar(50) not null
)
insert into Country Values(1,'India')
insert into Country Values(2,'USA')
2- Create a New MVC Project named BindDropDownMVC3 with Razor ViewEngion. in Models Folder add a EDMX file and add Country TAble in EDMX.
3- Add a Model Class named CountryModel.cs. below are the Code specified....
public class CountryModel
{
public string Country { get;
set; }
public List<SelectListItem>
Countrylist { get; set;
}
public void SetCountryList(List<Country> countries)
{
List<SelectListItem> items = new List<SelectListItem>();
countries.ToList().ForEach(s =>
{
items.Add(new SelectListItem()
{
Text =
s.CountryName.ToString(),
Value = s.CountryID.ToString()
});
});
this.Countrylist
= items;
}
}
4- in DefaultController.cs add the Following Code
using BindDropDownMVC3.Models;
public class DefaultController
: Controller
{
EmployeeDataEntities
ed= new EmployeeDataEntities
();
//
// GET:
/Default/
public ActionResult Index()
{
CountryModel
cm = new CountryModel();
cm.SetCountryList(GetCountries());
return
View(cm);
}
public List<Country>
GetCountries()
{
return
(from c in
ed.Countries.OrderBy(x=> x.CountryID) select
c).ToList();
}
}
5- Now in Index.cshtml add the Following Code
@model BindDropDownMVC3.Models.CountryModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.DropDownListFor(model => model.Country,
Model.Countrylist, new { @id = "countryid", style = "font-family:Calibri;width: 213px; border: 1px solid
#828282;"})
@Html.DropDownList("dd1",Model.Countrylist)
6- Now Run your Application.
0 comments:
Post a Comment