Bind Drop Down List In MVC

1. Bind DropDown with hard coded values

We will try to write both controller code and view in every case, so let's see our first example by using hard coded value

    public ActionResult Index()
    {       
        ViewBag.Active = new List<SelectListItem> {                  
                 new SelectListItem { Text = "Yes", Value = "1"},                   
                 new SelectListItem { Text = "No", Value = "0"}
             };
        var model = new ProductModel();
        return View(model);
    }

In the view, I am not going to show all the label and other model detail. Here IsActie is the model value which will come from database for existing records otherwise null or default value fromthe model, I used the class name from bootstrap.

@Html.DropDownListFor(model => model.IsActive,
   new SelectList(ViewBag.Active, "Value", "Text"), 
   "Select status",
    new { @class = "form-control" })

If it is hard coded values and is a big list then we can create a separate method to create the list otherwise directly we can declare it in view rather than passing from controller view as we did in our above example, see how

@Html.DropDownListFor(model => model.Category,
    new SelectList(new List<SelectListItem> {                  
             new SelectListItem { Text = "Yes", Value = "1"},                   
             new SelectListItem { Text = "No", Value = "0"}
         }, "Value", "Text"), 
    "Select status",
     new { @class = "form-control" })

It doesn't looks good but good thing is that we don't need to create the list again and again on postback, which we will see latter.


2. Bind DropDown with records from database

If you will explore a little bit, you will found most of the people suggest to convert the record into SelectList in controller or in model before passing to view. Is that really required or is a good practice? I cannot say about others but for me, it is really frustrating to convert my table into SelectList every time. If not then is there any way to directly bind the dropdown from a table records, yes, we will see it in this example:

I have a table category which we will use in this example, here is the table structure:

public partial class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public bool IsActive { get; set; }
}

Controller code:

// GET: Products
public ActionResult Create()
{
    var db = new MyDBEntities();
    ViewBag.Categories = db.Categories.Where(x => x.IsActive);
    var model = new ProductModel();
    return View(model);
}   

// POST: Create Product
public ActionResult Create(ProductModel model)
{
    var db = new MyDBEntities();
    if (ModelState.IsValid)
    {
        // code to save record  and redirect to listing page
    }
    // If model is not valid then reload categories from database
    ViewBag.Categories = db.Categories.Where(x => x.IsActive);
    return View(model);
}

In our GET action we are fetching all active categories from database and passing to view by using ViewBag. In POST action we try to validate the posted data by using ModelState.IsValid method, if valid, save data and redirect user to your desired page otherwise, re-populate the the categories before returning the user to page to fix the issue. Now we will see our view html

@Html.DropDownListFor(model => model.Category,
    new SelectList(ViewBag.Categories, "CategoryID", "CategoryName"), 
    "Select Category",
    new { @class = "form-control" })

As you noticed, we directly pass the table records to view after fetching from database without converting to Select List and converted into Select List directly into the view, which is easy and save time. If we will do the same in controller then we need to convert the list in both GET as well as POST action.


3. Bind DropDown with Enum

There are two ways to bind and save the records, and it's all depends on requirement, whether we want to save the number or text value of the enum, we will try both. Let's first create an enum say Language, I am adding those language which I read write and speak

public enum Language
{
    Arabic,
    English,
    Hindi,
    Spanish,
    Urdu
}

If we need to save the text or say bind with text then

// In controller
ViewBag.Languages = Enum.GetValues(typeof(Language)).Cast<Language>();

// In View
@Html.DropDownListFor(model => model.Language,
        new SelectList(ViewBag.Languages),
        "Select language",
        new { @class = "form-control" })

As in most cases we want to use value and text, so we need to create a structure or class and create the list of it from enum which we will use in this example:

We will create a structure which we can use for entire application

public struct DDL
{
    public int Value { get; set; }
    public String Text { get; set; }
}

Now create the list of DLL by using Language enum foreach, and assign to ViewBag.Languages

var languages = new List<DDL>();
foreach (Language lang in Enum.GetValues(typeof(Language)))
    languages.Add(new DDL { Value = (int)lang, Text= lang.ToString() });

ViewBag.Languages = languages;

In view, binding is same as earlier:

@Html.DropDownListFor(model => model.Language,
      new SelectList(ViewBag.Languages, "Value", "Text"),
      "Select status",
      new { @class = "form-control" })




要查看或添加评论,请登录

Jayesh Patil的更多文章

  • (MicroSoft.net MVC)

    (MicroSoft.net MVC)

    Small Introduction Of Model View Controller Model The Model component corresponds to all the data-related logic that…

社区洞察