MVC DropDownList NOT设置已选中

时间:2014-10-11 11:12:43

标签: asp.net-mvc-4 enums html.dropdownlistfor selected

我有一个View for Update操作,我的模型有enum属性:

public enum DeliveryStatusType
{
    Active = 1,
    Deactive = 2,
}

基本上,我填充enum并使用DropDownList。为了理解发生了什么,我将其简化并尽可能简单地发布在这里。

我已经尝试了Html.DropDownListHtml.DropDownListFor,这里是视图:

第一个示例(未在此处设置所选内容)

@Html.DropDownListFor(model => model.DeliveryStatus, new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "1" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "2" }}) //Notice that I manually set the 2nd true

第二个例子(未在此处设置选择)

@Html.DropDownList("DeliveryStatus", new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "1" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "2" }}) //Notice that I manually set the 2nd true

但是,我意识到当我设置SELECT html元素的名称和ID 而不是 DeliveryStatus时(假设为DeliveryStatus1) ,它神奇地起作用!

第3个示例(在此处设置所选内容)

@Html.DropDownList("DeliveryStatus1", new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "1" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "2" }}) //Notice that I manually set the 2nd true

但是当我这样做并设置为DeliveryStatus1时,我无法将数据发布到Controller

这有什么问题或我做错了什么? 我需要能够设置所选数据并将其重新发送回来

2 个答案:

答案 0 :(得分:2)

感谢Stephen Muecke,对于enums,我将值设为Enum.ToString()而不是整数值。:

@Html.DropDownListFor(model => model.DeliveryStatus, new SelectListItem[] {
        new SelectListItem { 
            Selected = false, 
            Text = "Active Delivery", 
            Value = "Active" },
        new SelectListItem { 
            Selected = true, 
            Text = "Deactive Delivery", 
            Value = "Deactive" }})

答案 1 :(得分:0)

对我有用的是确保model.Xyz变量是一个字符串,然后使用" Selected = true"使其成为默认选定值。

@Html.DropDownListFor(model => model.TopN, new SelectListItem[]
{
    new SelectListItem() { Text = "10", Value = "10", Selected = false },
    new SelectListItem() { Text = "20", Value = "20", Selected = false },
    new SelectListItem() { Text = "50", Value = "50", Selected = true },
    new SelectListItem() { Text = "100", Value = "100", Selected = false },
    new SelectListItem() { Text = "500", Value = "500", Selected = false }
})