[英]Returning an ActionResult from another ActionResult
說我有以下代碼,在記事本中嘲笑,所以原諒任何小錯誤:)
//Default page
public ActionResult Index()
{
var musicViewModel
{
Albums = GetTopSellingAlbums(5),
Genres = GetTopGenres(5),
Artists = GetTopArtists(5)
};
return View(musicViewModel);
}
[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
//For the example, pretend I have a class called musicStoreSubmission in my
//viewmodel which holds a few different fields the user fills out.
if(ModelState.IsValid)
{
//Do some actions based on the user submitting a form
}
//Else, refresh page with errors in Modelstate.
var musicViewModel
{
Albums = GetTopSellingAlbums(5),
Genres = GetTopGenres(5),
Artists = GetTopArtists(5)
};
return View(musicViewModel);
}
我關注的是,為了回發模型狀態無效的任何錯誤,我需要再次生成視圖模型,以便可以創建頁面上使用這些對象的任何元素(流派,藝術家等)。 問題是它需要我將ActionResult中的一些代碼復制並粘貼到ActionResult,似乎使我的代碼不是很干。
有沒有更好的方法來避免這樣的重復代碼? 目前我只是將viewmodel需要的任何默認對象的生成移動到一個單獨的方法和/或構造函數中,但是由於我必須生成整個控制器可能需要的所有對象,所以它有點亂。 我希望我能做的就是將我的第二個Index Action指向第一個Index Action,並將其作為常規方法使用。 雖然我嘗試了幾種不同的方法,但似乎無法將ActionResult返回到另一個ActionResult中。
有什么想法嗎?
我建議應用Post / Redirect / Get模式。 它非常適合MVC網絡應用程序。
檢查代碼示例的答案: ModelState.IsValid或Model.IsValid?
您可以返回另一個ActionResult方法,如下所示:
[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
if(ModelState.IsValid)
{
//Do some actions based on the user submitting a form
}
return MyAction();
}
或者您可以將發布的模型傳遞回ViewResult
[HttpPost]
public ActionResult Index(MusicViewModel musicViewModel)
{
if(ModelState.IsValid)
{
//Do some actions based on the user submitting a form
}
return View(musicViewModel);
}
第二種方法更好,因為您不重建ViewModel
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.