如何从DropdownListFor中获取值

本文关键字:获取 DropdownListFor | 更新日期: 2023-09-27 18:27:44

我不明白为什么Posted视图模型在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; }
---
---
}

有什么帮助吗?

如何从DropdownListFor中获取值

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

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

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