在DropDownList ASP.NET MVC中获取选定的项目
问题描述:
我知道有多个线程如何获取DropDownList的选定值.但是,我找不到从控制器的局部视图中获取此值的正确方法.
I know there are multiple threads on how to get the selected value of a DropDownList. However I can't find the right way to get this value from a partial view in my controller.
这是我的部分观点:
@model List<aptest.Models.answer>
@Html.DropDownList("dropdownlist", new SelectList(Model, "text", "text"))
<button type="submit">next</button>
答
为了获得下拉值,请将选择列表包装在一个表单标签中.使用模型和DropDownListFor
助手
In order to get dropdown value, wrap your select list in a form tag. Use models and DropDownListFor
helper
@model MyModel
@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
@Html.DropDownListFor(m => m.Gender, MyModel.GetGenderValues())
<input type="submit" value="Send" />
}
控制器和其他类
public class MyController : Controller
{
[HttpPost]
public ActionResult MyAction(MyModel model)
{
// Do something
return View();
}
}
public class MyModel
{
public Gender Gender { get; set; }
public static List<SelectListItem> GetGenderValues()
{
return new List<SelectListItem>
{
new SelectListItem { Text = "Male", Value = "Male" };
new SelectListItem { Text = "Female", Value = "Female" };
};
}
}
public enum Gender
{
Male, Female
}
如果您使用局部视图,只需在其中传递模型即可:
And if you use partial view, simply pass your model in it:
@Html.Partial("MyPartialView", Model)