0

我有一个下拉列表包含

{
   Select a title,
   Mr,
   Ms,
   Mrs
}

像这样初始化的

//in model file
Mymodel mm=new Mymodel();
mm.Titles=new []
{
   new SelectListItem{....}
}

.....
//in view file and was set up inside a form

@Html.DropDownListFor(m=>m.Title, Model.Titles,"Select a title");

单击提交按钮后,我想在下拉列表中获取选定的值。

4

1 回答 1

2

您可以让[HttpPost]提交表单的控制器操作采用与参数相同的视图模型:

[HttpPost]
public ActionResult SomeAction(Mymodel model)
{
    // the model.Title property will contain the selected value here
}

此外,Titles集合不会发送到您的 HttpPost 操作。这就是 HTML 的工作原理。<select>提交表单时仅发送元素的选定值。因此,Titles如果您打算重新显示相同的视图,则需要重新填充该属性。

例如:

[HttpPost]
public ActionResult SomeAction(Mymodel model)
{
    if (!ModelState.IsValid)
    {
        // there was a validation error, for example the user didn't select any title
        // and the Title property was decorated with the [Required] attribute =>
        // repopulate the Titles property and show the view
        model.Titles = .... same thing you did in your GET action
        return View(model);
    }

    // at this stage the model is valid => you could use the model.Title
    // property to do some processing and redirect
    return RedirectToAction("Success");
}
于 2013-02-25T07:01:53.177 回答