如何获得在MVC 4一个HTML下拉列表中的价值 [英] How to get the value of a html dropdown list in MVC 4
问题描述
我是新来的MVC,我创造了我的应用程序登记表,我想添加一个DropDownList,我codeD ahtml低于
I'm new to MVC and I'm creating a Registration form for my app and I want to add a dropdownlist and I coded ahtml dropdownlist like given below
<select id="drpType">
<option value="0">Single</option>
<option value="1">Married</option>
</select>
和我想要得到的选定值我怎么能做到这一点,以及如何创建MVC中默认@ Html.DropDownList对于上述方案
And I want to get the selected value how can I achieve that and how to create a default @Html.DropDownList in MVC for the above scenario
推荐答案
您应该给你的下拉列表中选择名称(ID是没有必要的):
You should give your dropdown a name (the id is not necessary):
<select id="drpType" name="drpType">
<option value="0">Single</option>
<option value="1">Married</option>
</select>
,然后在相应的控制器动作到表单提交,你可以有一个同名的参数,将包含选定的值:
and then in the corresponding controller action to which the form is submitted you could have a parameter with the same name which will contain the selected value:
[HttpPost]
public ActionResult SomeAction(string drpType)
{
// ... drpType will contain the selected value (0 or 1)
}
但要实现这一正确的方法是使用一个视图模型:
But the correct way to achieve this is to use a view model:
public class MyViewModel
{
[Display(Name = "Marital status")]
public string SelectedMaritalStatus { get; set; }
public IEnumerable<SelectListItem> MaritalStatuses
{
get
{
return new[]
{
new SelectListItem { Value = "0", Text = "Single" },
new SelectListItem { Value = "1", Text = "Married" },
};
}
}
}
和然后,你可以有2个操作(一个用于呈现的形式,一个用于处理的结果)的控制器:
and then you could have a controller with 2 actions (one for rendering the form and one for processing the results):
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// ... model.SelectedMaritalStatus will contain the selected value (0 or 1)
}
}
现在你可以有一个强类型的视图中,你可以使用DropDownListFor助手:
and now you could have a strongly typed view in which you can use the DropDownListFor helper:
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.SelectedMaritalStatus)
@Html.DropDownListFor(x => x.SelectedMaritalStatus, Model.MaritalStatuses)
</div>
<button type="submit">OK</button>
}
这篇关于如何获得在MVC 4一个HTML下拉列表中的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!