Bind Html.DropDownList with static items

放肆的年华 提交于 2019-11-27 20:13:32
Sreekumar P

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) %>

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" }
                 }) 

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.

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)
Paul Makram Fares

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>
Siva Ragu
<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>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!