DropDownList in MVC


In mvc we can create dropdown list using html helper with class and without class.

Example of DropDownList without Class

In the following example, we are creating dropdownlist to select gender. As we know that in general dropdown list we show data in Text and Value format.

@Html.DropDownList("ddl1",new List<SelectListItem>() { new SelectListItem() { Text="Male",Value= "m" }, new SelectListItem() {Text="Female",Value="f", Selected=true } })

Example of DropDownList using Class

Here we create a class, which contains the property for Text and Value. In this example, I am creating dropdown list for countries. In which I am taking CID as a value field and CName as a Text Field.
Create controller name home and method index and create view for index method.
To add properties, add class and give it name country and declare two properties CID and CName.

  
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication7
{
    public class country
    {
        public int CID { get; set; }
        public string CName { get; set; }
    }
}

  
Now go to your index view and create a list of type country and add Items in this list.


  
 @{
    Layout = null;

    List<MvcApplication7.country> lst_country = new List<MvcApplication7.country>()
    {

        new MvcApplication7.country{CID=1, CName="India"},
        new MvcApplication7.country{CID=2, CName="USA"},
        
    };
}
  
Now create dropdownlist using HTML Helper class.
@Html.DropDownList("drp_country", new SelectList(lst_country, "CID", "CName"))
In this DropDownList drp_country is id and Name for this control. We added SelectList in which we pass data source which is List and the name of ValueField and TextField.

Complete Code


  
  @{
    Layout = null;

    List<MvcApplication7.country> lst_country = new List<MvcApplication7.country>()
    {

        new MvcApplication7.country{CID=1, CName="India"},
        new MvcApplication7.country{CID=2, CName="USA"},
        
    };
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    
    @Html.DropDownList("drp_country", new SelectList(lst_country, "CID", "CName"))

</body>
</html>

  
The output of this code is as follows:-


No comments:

Post a Comment