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 に答える