Click here to Skip to main content
Click here to Skip to main content

Tagged as

How to fill dropdown in ASP.NET MVC 3?

, 14 Nov 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Amey K Bhatkar
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
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun14-Nov-13 20:59 
GeneralRe: My vote of 5 PinprofessionalAmey K Bhatkar15-Nov-13 6:28 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141022.2 | Last Updated 14 Nov 2013
Article Copyright 2013 by Amey K Bhatkar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid