Friday, July 13, 2012

Bind data to dropdownlist in Asp.net MVC4

In previous articles we have seen how to bind data to dropdownlist in gridview in asp.net,How to create entity data model in MVC,Give the reference to css/java script file in ASP.NET MVC,.In this post i will give an example for binding data to drop downlist with static data and dynamic data(From DataBase) in MVC.To assign the items to drop downlist statically,First we have to put the items into SelectListItem array  in controller.Then we can bind those items to drop down in View
Model:

using System.Web;
using System.Web.Mvc;
using System.Configuration;

namespace Dropdown.Models
{
public class Dropdwon
{
public SelectListItem[] sli { set; get; }
}
}
Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Dropdown.Models;

namespace Dropdown.Controllers
{
public class DropdownController : Controller
{
// GET: /Dropdown/
public ActionResult Index()
{
var sli = new[]{
new SelectListItem {Text = "India"},
new SelectListItem {Text = "US" },
new SelectListItem {Text = "UK" },
new SelectListItem {Text = "Australia" }
};
ViewData["ddlcountryname"] = sli;
return View(sli);
}

}
}
Index.cshtml
@{

    ViewBag.Title = "This is my test";

}

<h2>Bind data to dropdown list in mvc4</h2>

@Html.DropDownList("ddlcountryname")

Using Entity model To bind data:
I have used entity model to bind the data to dropdown from database.Whenever we create a connection we can get  model with our data base.Then we can write LINQ query to get the desired data.Finally we need to convert the data to SelectList from query data

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Dropdown.Models;

namespace Dropdown.Controllers
{
public class CityController : Controller
{
private Test_KrishnaEntities db = new Test_KrishnaEntities();
 
// GET: /City/

public ActionResult Index()
{
List x = new List(); 
var city = from contact in db.Contacts orderby contact.Name
                         select contact.Name;
x.AddRange(city.Distinct());
ViewData["ddlcountryname"] =new  SelectList(x);
return View();
}
}

}

6 comments:

First interview questions said...

nice post......

First interview questions said...
This comment has been removed by the author.
Anonymous said...

Very nice, very accessibly! Exactly that i was looking about, found it through google images, maybe something bad with tags

Bhaskara said...

Thanks for comment.i will rename the tags for this

Anonymous said...

Thank you! Spent 3 hours looking for how to populate a dropdown from my database. The lack of useful documentation on this is shocking.

Dominic Tooth said...

The method you provided for data binding is worth to try for effective result. I specially liked the way you illustrate to do that using "Entity model".

Bel