如何从DropdownListFor获取价值?

时间:2013-08-15 14:33:10

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

我无法弄清楚为什么发布的viewmodel没有在DropdownListFor中选择值。相反,它正在显示Ids。

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

在Controller 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; }
---
---
}

任何帮助?

2 个答案:

答案 0 :(得分:0)

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

这就是下拉列表只返回ID(下拉菜单的值部分)的原因。在那里,您可以在第一个位置填充下拉列表时确定每个项目的文本,因此必须能够将它们重新绑定。

答案 1 :(得分:0)

SelectList中,当您提交表单时,它将是您的词典中POST的键,而不是词典中的值。如果您想要提交的值,请使用字符串值作为键。这是一个在视图中构建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" })