Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.DropDownListFor how to set default value [duplicate]

@Html.DropDownListFor(model => model.Status, new List<SelectListItem>         { new SelectListItem{Text="Active", Value="True"},          new SelectListItem{Text="Deactive", Value="False"}}) 

In view I am using this drop dowenlist coding. I run my application default deactive value is display in dropdown list box. I want display default Active

like image 528
satheeshkumarMCA Avatar asked May 22 '14 06:05

satheeshkumarMCA


People also ask

How to set default value for dropdownlistfor?

If you are creating the SelectListItem s dynamically, you can just set the one you want as Selected = true and it will then be the default.

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.


2 Answers

Like this:

@Html.DropDownListFor(model => model.Status, new List<SelectListItem>         { new SelectListItem{Text="Active", Value="True"},          new SelectListItem{Text="Deactive", Value="False"}},"Select One") 

If you want Active to be selected by default then use Selected property of SelectListItem:

@Html.DropDownListFor(model => model.Status, new List<SelectListItem>             { new SelectListItem{Text="Active", Value="True",Selected=true},              new SelectListItem{Text="Deactive", Value="False"}},"Select One") 

If using SelectList, then you have to use this overload and specify SelectListItem Value property which you want to set selected:

@Html.DropDownListFor(model => model.title,                       new SelectList(new List<SelectListItem>   {       new SelectListItem { Text = "Active" , Value = "True"},       new SelectListItem { Text = "InActive", Value = "False" }   },     "Value", // property to be set as Value of dropdown item     "Text",  // property to be used as text of dropdown item     "True"), // value that should be set selected of dropdown      new { @class = "form-control" }) 
like image 51
Ehsan Sajjad Avatar answered Sep 18 '22 09:09

Ehsan Sajjad


SelectListItem has a Selected property. If you are creating the SelectListItems dynamically, you can just set the one you want as Selected = true and it will then be the default.

SelectListItem defaultItem = new SelectListItem() {    Value = 1,    Text = "Default Item",    Selected = true }; 
like image 29
Elad Lachmi Avatar answered Sep 18 '22 09:09

Elad Lachmi