asp.net-mvc 在 DropDownList ASP.NET MVC 中获取所选项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22706345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get selected item in DropDownList ASP.NET MVC
提问by JaperTIA
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.
我知道有多个线程关于如何获取 DropDownList 的选定值。但是,我找不到从控制器的局部视图中获取此值的正确方法。
This is my partial view:
这是我的部分观点:
@model List<aptest.Models.answer>
@Html.DropDownList("dropdownlist", new SelectList(Model, "text", "text"))
<button type="submit">next</button>
回答by Andrei
In order to get dropdown value, wrap your select list in a form tag. Use models and DropDownListForhelper
为了获得下拉值,请将您的选择列表包装在一个表单标签中。使用模型和DropDownListFor助手
Razor View
剃刀视图
@model MyModel
@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
@Html.DropDownListFor(m => m.Gender, MyModel.GetGenderValues())
<input type="submit" value="Send" />
}
Controller and other classes
控制器和其他类
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)
回答by rb4bhushan
ViewData["list"] = myList.ToList();
Razor
剃刀
@Html.DropDownList("ddl", new SelectList((System.Collections.IEnumerable)ViewData["list"], "Id", "Name"))
Controller
控制器
public ActionResult ActionName(String ddl)
{
// now ddl has your dropdownlist's selected value i.e Id
}

