Tuesday 20 August 2013

Binding Data with Razor Dropdown Control in MVC3-EntityFramework

In this demo we are binding a Country Name Column with Razor Dropdown.
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

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives