Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to fill dropdown in ASP.NET MVC 3?

0.00/5 (No votes)
14 Nov 2013 1  
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 | :).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here