Click here to Skip to main content
15,886,873 members
Articles / Web Development / ASP.NET
Tip/Trick

How to fill dropdown in ASP.NET MVC 3?

Rate me:
Please Sign up or sign in to vote.
4.88/5 (8 votes)
14 Nov 2013CPOL2 min read 63K   1.8K   11   2
How to fill dropdown in ASP.NET MVC 3?

Q) How to fill dropdown in ASP.NET MVC 3?  

The DropDownList control is used to create a drop-down list. Each selectable item in a DropDownList control is defined by a ListItem element. SelectListItem consist of the text and value pair. Text is display on the dropdown list where each text is assigning with value that server is known. MVC 3 provide Html.DropDownList helper method that have overload DropDownList(String name, IEnumerable<SelectListItem> selectList) where name is the id of the dropdownlist and selectList is list items. 

Consider table name:- Students 

Column Name  

  • Rollnumber [Primary Key] 
  • Name
  • Division

We are displaying student name in dropdown text and store rollnumber as value. When user select student name it's division will get display in textbox. As rollnumber is primary key two students having same name can be differentiate based on rollnumber. Let's start building our requirement. 

Let's create simple ViewModel class name student. Our view display drop down list which accept collection of SelectListItem let's create property for list of SelectListItem. 

C#
namespace DropDownListDemo.ViewModel
{
    public class Student
    {
        public IList<SelectListItem> Drp_Names { get; set; }
    }
} 

I have use ADO.NET Entity data model [.edmx file] and created the context class of entities. Let's fetch rollnumber and name of student from student_db table and assign to property Drp_Names.

C#
DemoEntities demoContext = new DemoEntities();
public ActionResult FillDropDwon()
{
    Student student=new Student();
    student.Drp_Names = (from s in demoContext.Student_db
                         select new SelectListItem()
                         {
                             Text = s.Name,
                             Value =SqlFunctions.StringConvert((double)s.RollNumber)
                         }).ToList<SelectListItem>();
    return View(student);
}

I have pass Student class object to view as model. Let's create strongly typed view of  Student Class.

C#
@model DropDownListDemo.Bisiness.Student
@{
    ViewBag.Title = "FillDropDwon";
}

<h2>FillDropDwon</h2>
@Html.DropDownList("StudentsList", Model.Drp_Names, "Select", new {onchange="GetDiv()"})
<br />
Student Division:- @Html.TextBox("myTextBox") 

Now we have fill our dropdownlist with student name as text and rollnumber as value. On change of the text in dropdownlist we will display student division in the textbox. Let's write jQuery function GetDiv that will trigger on OnChange event of DropDownList.

JavaScript
<script>
    function GetDiv() {
        var rollNumber = $('#StudentsList').val();
        $.ajax(
        {
         type: "POST",
         url: "@Url.Action("GetDivOfStudent","Home")",
         dataType: 'text',
         data: { id: rollNumber },
         success: function (result) {
             $('#myTextBox').val(result);      
         },
        error: function (req, status, error) {
            alert("Coudn't load partial view"+error+req);
        }
});
}</script> 

jQuery function will make Ajax call to the action method GetDivOfStudent(int id). Action method GetDivOfStudent accept rollnumber as argument. Rollnumber is primary key, let's retrieved division based on rollnumber of student and return division of student to the Ajax call. On success of Ajax call let's assign division to the textbox.  

C#
[HttpPost]
public ActionResult GetDivOfStudent(int id)
{
    var div = (from s in demoContext.Student_db
               where s.RollNumber == id
               select s.Div).FirstOrDefault();
    return Content(div);
} 

Please have a look at attached code for more clarity. Happy coding Smile | :).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Lionbridge
India India
Amey K Bhatkar, a “Microsoft .Net” Web Developer.
I am programmer by will and profession.
I have completed my MCA in 2011 and join software industry.
Presently I am working with Lion Bridge Technologies in Mumbai - India

Comments and Discussions

 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun14-Nov-13 20:59
Humayun Kabir Mamun14-Nov-13 20:59 
GeneralRe: My vote of 5 Pin
Amey K Bhatkar15-Nov-13 6:28
Amey K Bhatkar15-Nov-13 6:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.