Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to bind DropDown using model in Asp.Net MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 334
    Comment on it

    How to bind DropDown using model in Asp.Net MVC

    For Binding the Dropdown using Model, we have to follow the following steps:-

    Step 1: First create a model as follows:-

    Example:

    Public Class DropdownBind
    {
    public List<SelectListItem> lst { get; set; } 
    public int selectedItem { get; set; }
    }
    

    Step 2: Now in the controller fill the model either by creating an instance of List<SelectListItem> and adding items to it or by getting the values from Database .

    For Example:

    I Method: Creating an instance of List<SelectListItem> and adding items to it, and finally copying it to the List<SelectListItem> lst of the model.

    public ActionResult BindDropDown()
    {
    List<SelectListItem> items = new List<SelectListItem> ();
    
    items.Add(new SelectListItem
    {
    Text = "Item1",
    Value= "1"
    });
    
    items.Add(new SelectListItem
    {
    Text = "Item2",
    Value= "2"
    });
    
    var model = new DropdownBind()
    {
    lst = items,
    selectedItem = 1
    };
    
    return View(model);
    }
    

    II Method: Getting value from DataBase:

    DropdownBind model = new DropdownBind();
    
    model.lst = new SelectList(GetDataFromDataBase(), "Value", "Text"); 
    

    GetDataFromDataBase() function will get the values from database (This is not discussed in this blog) and will bind it to the List<SelectListItem> lst of the model.

    Step 3: Now create a strongly typed View for the DropdownBind model by clicking on the BindDropDown() Action Method , this will aotamticaly create the code for the Dropdown in the View page.

    Example:

     @Html.DropDownListFor("selectedItem ", Model.lst)
    

    To display the default value we can add a third parameter as follows:

    @Html.DropDownListFor("selectedItem ", Model.lst, "--Select Value--")
    

    For postback we can add the fourth parameter as follows:

    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new {id="Form" }))
    {
    
    @Html.DropDownList("selectedItem ", Model.lst, "--Select Value--",
    new
    {
    onchange = "document.getElementById('Form').submit();"
    })
    
    }
    

    Hope it helps...!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: