[英]getting the value of dropdownlist in MVC4
我是MVC的新手,请告诉我如何在控制器中检索选定的dropdownlist值,这是将值添加到dropdownlist的方法
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "What is your Place of Birth?", Value = "What is your Place of Birth?" });
items.Add(new SelectListItem { Text = "What is your favourite Book?", Value = "What is your favourite Book?" });
items.Add(new SelectListItem { Text = "What is your childhood friend name?", Value = "What is your childhood friend name?" });
items.Add(new SelectListItem { Text = "What is your first car make and model?", Value = "What is your first car make and model?" });
items.Add(new SelectListItem { Text = "What is your favourite place?", Value = "What is your favourite place?" });
ViewData["ddlitems"] = items;
查看文件
@Html.DropDownList("ddlitems")
在模型上,为该值提供一个属性:
class ModelClass
{
public string DropdownValue{get; set;}
}
然后使用以下Razor语法
@Html.DropdownListFor(m => m.DropdownValue, "ddItems");
这将创建一个与Model属性相同名称的下拉列表,它应自动与模型一起回发
获取所选选项的值的最简单方法是使元素的ID与要发布到ActionResult
的元素的ID匹配。 因此,如果您的select
元素呈现为;
<select id="SomeID">
<option value="What is your Place of Birth?">What is your Place of Birth?</option>
</select>
然后将其发布到ActionResult
[HttpPost]
public ActionResult MyActionResult(string SomeID){
// SomeID = What is your Place of Birth?
Return View();
}
在您的情况下,这可能是最简单的选择,因为您没有要传递给View
的强类型对象。 另请注意,这将与您发布的任何表单元素一起使用。 只需将ID与ActionResult
上的参数进行匹配即可。
更进一步,您可能最好阅读ASP.Net MVC中的模型绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.