0

我是 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")
4

2 回答 2

0

在您的模型上,具有值的属性:

class ModelClass
{
    public string DropdownValue{get; set;}
}

然后使用以下 Razor 语法

@Html.DropdownListFor(m => m.DropdownValue, "ddItems");

这将创建一个与 Model 属性名称相同的下拉列表,它应该自动与模型一起回发

于 2013-08-21T10:33:17.390 回答
0

获取所选选项值的最简单方法是将元素的 ID 与您发布到ActionResult. 因此,如果您的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 中的模型绑定。

于 2013-08-21T10:40:47.427 回答