我是MVC的新手告诉我如何在控制器中检索所选的下拉列表值 这是我如何将值添加到下拉列表
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")
答案 0 :(得分:0)
在您的模型上,拥有值的属性:
class ModelClass
{
public string DropdownValue{get; set;}
}
然后使用以下Razor语法
@Html.DropdownListFor(m => m.DropdownValue, "ddItems");
这将创建一个名为与Model属性相同的下拉列表,它应该自动回复模型
答案 1 :(得分:0)
获取所选选项值的最简单方法是将元素的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
上的参数进行匹配。
为了更进一步,您可能最好阅读Model Binding within ASP.Net MVC.