Various ways to show DropDownList (select element in HTML) in MVC

Views: 1235
Comments: 0
Like/Unlike: 0
Posted On: 14-Jun-2016 06:38 

Share:   fb twitter linkedin
Rahul M...
4918 Points
28 Posts

Introduction

In Webform application, there are many drag and drop controls for dropdownlist. But in MVC creating dropdownlist is totally different. In MVC HtmlHelper provides different extension method to bind or populate the dropdownlist in view.
There three extension methods of HtmlHelper as follows

  • Html.DropDownList
  • Html.DropDownListFor
  • Html.EnumDropDownListFor

Prerequisites

  • need to know how to pass model to the view
  • Basic knowledge of MVC Architecture

Html.DropDownList

It returns a select HTML element that lets users select one item. You can use in various ways

Using Model

@Html.DropDownList("RoleId", Model.RoleList)

Using ViewBag

@Html.DropDownList("RoleId", ViewBag.RoleList as SelectList)

Using ViewData

@Html.DropDownList("RoleId", ViewData["RoleList"] as SelectList)

Hardcode values on View

@Html.DropDownList("RoleId", new List<SelectListItem>
{ new SelectListItem { Text = "Admin", Value = "1", Selected=true},
new SelectListItem { Text = "Member", Value = "2"},
new SelectListItem { Text = "User", Value = "3"}
}, "Select Role")

Html.DropDownListFor

It returns an HTML select element for each property in the object that is represented by the specified expression. It can be used for stongly typed view.
You can use in various ways

Using Model

@Html.DropDownListFor(M => M.RoleId, new SelectList(Model.RoleList, "Value", "Text"))
@Html.DropDownListFor(M => M.RoleId, new SelectList(Model.RoleList, "Value", "Text"), "Select Role", new { @class = "cssclass" });

Html.EnumDropDownListFor

It returns an HTML select element for each value in the enumeration that is represented by the specified expression.

@Html.EnumDropDownListFor(m => m.RoleEnum, "Select a Role", new { @class = "cssclass" })

Conclusion

From above description, I hope you can able to use different form of dropdownlist.

 

0 Comments
 Log In to Chat