1

如何从控制器的视图上的下拉列表中获取选定的值?

模型:

public class CustomerInformation
{
    public Dictionary<int, string> State { get; set; }
    public CustomerInformation()
    {
        State = new Dictionary<int, string>()
        {
            { 0, "California"},
            { 1, "Nevada"}
        };
    }
}

控制器

public ActionResult Index()
{
    var model = new CustomerInformation.Models.CustomerInformation();
    return View(model);
}

public ActionResult ShowData(CustomerInformation.Models.CustomerInformation _customerInformation)
{
   //..
}

看法

@using (Html.BeginForm("ShowData", "Home"))
{
    @Html.Label("State:: ");
    @Html.DropDownListFor(m => m.State, new SelectList(Model.State, "Key", "Value"))   
    <input type="submit" value="Submit" />
}
4

2 回答 2

1

您需要StateId模型的属性。然后你可以在你的发布价值中得到它......

public class CustomerInformation
{
    public Dictionary<int, string> State { get; set; }
 public int StateId {get;set;}   
 public CustomerInformation()
    {
        State = new Dictionary<int, string>()
        {
            { 0, "California"},
            { 1, "Nevada"}
        };
    }
}

这是您要更改 html 选择列表的 id 和名称的地方:

@Html.DropDownListFor(m => m.StateId, new SelectList(Model.State, "Key", "Value"))   

然后在您的 Post 方法中:

public ActionResult ShowData(CustomerInformation.Models.CustomerInformation _customerInformation)
{
   _customerInformation.StateId // The selected value.
} 
于 2013-09-13T21:24:22.480 回答
0

我需要添加到我的模型中

public int id { get; set; }

保存推算的选定下拉值

然后在我看来分配该值

@Html.DropDownListFor(m => m.id, new SelectList(Model.State, "Key", "Value"))
于 2013-09-13T21:57:03.827 回答