【问题标题】:How to get value from DropdownListFor?如何从 DropdownListFor 中获取价值?
【发布时间】:2013-08-15 14:33:10
【问题描述】:

我无法弄清楚为什么 Posted viewmodel 没有在 DropdownListFor 中选择值。相反,它在其中显示 Id。

在控制器 HttpGet 编辑操作中:

      model.MaritalStatuses = new SelectList(maritalStatuses, "Key", "Value", 0);
     ---
     ---
    static Dictionary<int, string> maritalStatuses = new Dictionary<int, string>()
 {
        {0, "--Select One---"},
        {1, "Unmarried,"},
        {2, "Divorced, "},
        {3, "Widowed,  "},
        {4, "Separated,"},
        {5, "Annulled  "}
    };

查看:

 @Html.DropDownListFor(model => model.MaritalStatus, Model.MaritalStatuses,"--Select One--" , new { @class = "form-control" })

在控制器 HttpPost 编辑操作中:

     public ActionResult Edit(ProfileViewModel model)
            {
    ---
    // Here I get Keys in Property instead of Values in DropdownListFor
//For example : MaritalStatus =2    
---
    }

在 ProfileViewModel 中:

public class ProfileViewModel
    {
---
---
 public string MaritalStatus { get; set; }
        public SelectList MaritalStatuses { get; set; }
---
---
}

有什么帮助吗?

【问题讨论】:

    标签: c# asp.net-mvc-4 razor html.dropdownlistfor


    【解决方案1】:

    SelectList 中,提交表单时将是您的字典中的键POSTed,而不是字典中的值。如果您想要提交的值,请使用字符串值作为键。这是一个在视图中构建 SelectListItem 实例的示例(我个人更喜欢这样做):

    static List<string> maritalStatuses = new List<string>()
    {
        "Unmarried",
        "Divorced",
        "Widowed",
        "Separated",
        "Annulled"
    };
    
    public class ProfileViewModel
    {
    
     public string MaritalStatus { get; set; }
    
     public IList<string> MaritalStatuses { get { return maritalStatuses; } }
    }
    
    @Html.DropDownListFor(model => model.MaritalStatus, 
                          Model.MaritalStatuses.Select(s => new SelectListItem 
                              { 
                                  Text = s, 
                                  Value = s 
                              }, 
                          "--Select One--", 
                          new { @class = "form-control" })
    

    【讨论】:

      【解决方案2】:

      ID(值)是唯一的,而描述不能保证是唯一的,因此不能依赖于准确的选择信息。

      这就是为什么下拉列表只会返回 ID(下拉列表的值部分)的原因。从那里您可以在首先填充下拉列表时确定每个项目的文本,因此必须能够将它们重新绑定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-01
        • 2018-04-07
        • 2021-12-26
        • 2016-08-24
        • 2012-11-29
        • 2018-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多