0

我无法弄清楚为什么 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; }
---
---
}

任何帮助?

4

2 回答 2

0

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

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

于 2013-08-15T14:36:55.150 回答
0

在 中SelectList,它将POST是提交表单时编辑的 Dictionary 中的键,而不是 Dictionary 中的值。如果您想要提交的值,请使用字符串值作为键。这是一个在视图中构建 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" })
于 2013-08-15T14:37:05.853 回答