如何从控制器的视图中获取从下拉列表发送的选定值?
型号:
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" />
}
答案 0 :(得分: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.
}
答案 1 :(得分:0)
我需要添加到我的模型
public int id { get; set; }
保持估算的选定下拉值
然后在我的视图中分配该值
@Html.DropDownListFor(m => m.id, new SelectList(Model.State, "Key", "Value"))