Bind Html.DropDownList with static items
Asked Answered
C

6

17

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?

Codding answered 7/4, 2011 at 5:7 Comment(0)
H
27

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) %>
Hamitic answered 7/4, 2011 at 5:26 Comment(2)
But how we get the selected value on post?Codding
refer: altafkhatri.com/Technical/ASP_NET_MVC_Postback/…Hamitic
L
38

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" }
                 }) 
Linkoski answered 11/11, 2012 at 18:2 Comment(2)
I wish this response got more upvotes. Although some may claim that it is a best practice to pass the information from the view model to the view and then back to the controller, there are certainly situations where you don't want to go through all that hassle. This approach has much less code overall, so seems like a better solution (less code = better)Greensand
Ya, seems like a better solution (less code = better)Hermaphroditus
H
27

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) %>
Hamitic answered 7/4, 2011 at 5:26 Comment(2)
But how we get the selected value on post?Codding
refer: altafkhatri.com/Technical/ASP_NET_MVC_Postback/…Hamitic
B
5

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.

Bachelor answered 7/4, 2011 at 5:33 Comment(3)
Sorry I have tried your code but it gives an error - System.Web.Mvc.HtmlHelper<Models.WorkOrder>' does not contain a definition for 'DropDownListFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid argumentsCodding
Thanks iaimtomisbehave for your help. Sreekumar's solution worked for me.Codding
@Codding I also had the same problem, but changing the List<ListItem> to a List<SelectListItem> solved the problem (at least for me)Franco
J
1

if you want to be alittle explicity then try

        @{
            var domainsList = new SelectList(new []
            {
                new SelectListItem { Text = ".Com", Value = ".com", Selected = true },
                new SelectListItem { Text = ".Shopping", Value = ".shopping"},
                new SelectListItem { Text = ".Org", Value = ".org"},
                new SelectListItem { Text = ".Net", Value = ".net"},
                new SelectListItem { Text = ".AE", Value = ".ae"},
                new SelectListItem { Text = ".Info", Value = ".info"},
            }, "Value", "Text");
        }
        @Html.DropDownList("TopLevelDomains", domainsList)
Jamille answered 25/9, 2014 at 8:53 Comment(0)
N
0

This solved it for me:

 <td>
            @{  var RlistItems = new List<SelectListItem>();

                RlistItems.Add(new SelectListItem { Text = "Select Room Type", Value = "0" });
                RlistItems.Add(new SelectListItem { Text = "Meeting Room", Value = "1" });
                RlistItems.Add(new SelectListItem { Text = "Office", Value = "2" });
                RlistItems.Add(new SelectListItem { Text = "Cafeteria", Value = "3" });
            }

                @Html.DropDownListFor(model=>model.FirstOrDefault().RoomType
,RlistItems,RlistItems[item.RoomType.Value].Selected=true )
        </td>
Newlywed answered 18/1, 2018 at 13:39 Comment(0)
A
-1
<select asp-for="CountryName" asp-items=@(new List<SelectListItem> { new SelectListItem {Text="India",Value="1" } ,new SelectListItem {Text="Japan",Value="2" }} ) class="form-control">

<option>SELECT COUNTRY -- </option>

Adder answered 23/8, 2016 at 11:29 Comment(3)
<select asp-for="CountryName" asp-items=@(new List<SelectListItem> { new SelectListItem {Text="India",Value="1" } ,new SelectListItem {Text="Japan",Value="2" }} ) class="form-control"> <option>SELECT COUNTRY --</option> </select>Adder
A little explanation would boost the quality of your answer.Beehive
Although this code may help to solve the problem, it doesn't explain why and/or how it answers the question. Providing this additional context would significantly improve its long-term educational value. Please edit your answer to add explanation, including what limitations and assumptions apply.Toreador

© 2022 - 2024 — McMap. All rights reserved.