65.9K
CodeProject is changing. Read more.
Home

How to fill dropdown in ASP.NET MVC 3?

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (8 votes)

Nov 14, 2013

CPOL

2 min read

viewsIcon

63471

downloadIcon

1812

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. 

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.

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.

@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.

<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.  

[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 | :).