Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind Html.DropDownList with static items

I have to bind an Html.DropDownList with just two items statically.

Text="Yes" Value="1"
Text="No"  Value="0"

The important thing is that, I have to set the text and value fields.

How can I do this?

like image 809
Mukesh Avatar asked Apr 07 '11 05:04

Mukesh


3 Answers

I used this is properly working

        @Html.DropDownList("Status", new List<SelectListItem>

                 {
                    new SelectListItem{ Text="Active", Value = "1" },
                    new SelectListItem{ Text="Not-Active", Value = "0" }
                 }) 
like image 190
Saurabhbhatt Avatar answered Oct 18 '22 14:10

Saurabhbhatt


It is a best practice not to create the SelectList in the view. You should create it in the controller and pass it using the ViewData.

Example:

var list = new SelectList(new [] 
{
    new { ID = "1", Name = "name1" },
    new { ID = "2", Name = "name2" },
    new { ID = "3", Name = "name3" },
}, 
"ID", "Name", 1);

ViewData["list"]=list;
return View();

you pass to the constratctor: the IEnumerable objec,the value field the text field and the selected value.

in the View:

<%=Html.DropDownList("list",ViewData["list"] as SelectList) %>
like image 28
Sreekumar P Avatar answered Oct 18 '22 14:10

Sreekumar P


Code below assumes you are using razor view engine if not you will need to convert it.

@{
   var listItems = new List<ListItem>();
   listItems.Add(new ListItem{Text="Yes", Value="1"});
   listItems.Add(new ListItem{Text="No", Value="0"});
}

@Html.DropDownListFor(m=>m.SelectedValue, listItem);

You should consider creating the model in your code instead of the view. Also this would be a good candidate for an editor template.

like image 41
sarvesh Avatar answered Oct 18 '22 16:10

sarvesh