Tuesday, 20 August 2013

Binding Data with Razor Dropdown Control in MVC3-EntityFramework

Note:- if you are not aware of MVC, Entityframework in .NET, well this Post is not for you.

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

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)