C# 如何从DropdownListFor获取值?

C# 如何从DropdownListFor获取值?,c#,asp.net-mvc-4,razor,html.dropdownlistfor,C#,Asp.net Mvc 4,Razor,Html.dropdownlistfor,我不明白为什么发布的viewmodel没有在DropdownListFor中选择值。相反,它在其中显示ID 在控制器HttpGet编辑操作中: model.MaritalStatuses = new SelectList(maritalStatuses, "Key", "Value", 0); --- --- static Dictionary<int, string> maritalStatuses = new Dictionary<i

我不明白为什么发布的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  "}
    };
     public ActionResult Edit(ProfileViewModel model)
            {
    ---
    // Here I get Keys in Property instead of Values in DropdownListFor
//For example : MaritalStatus =2    
---
    }
在控制器HttpPost编辑操作中:

      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  "}
    };
     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; }
---
---
}
有什么帮助吗?

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


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

选择列表中,提交表单时,字典中的键是
POST
,而不是字典中的值。如果希望提交值,则使用字符串值作为键。下面是一个在视图中构建SelectListItem实例的示例(我个人更喜欢这样做):

静态列表maritalstatus=新列表()
{
“未婚”,
“离婚”,
“寡妇”,
“分离”,
“废止”
};
公共类profileview模型
{
公共字符串MaritalStatus{get;set;}
公共IList MaritalStatuses{get{return MaritalStatuses;}}
}
@Html.DropDownListFor(model=>model.MaritalStatus,
Model.MaritalStatuses.Select(s=>newselectListItem
{ 
Text=s,
值=s
}, 
“--选择一个--”,
新的{@class=“表单控制”})