Return an ActionResult from another ActionResult

Say I have the following code made in notepad, so sorry any minor bugs :)

//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); } 

My problem is that in order to return any errors with no ModelState, I need to create a viewmodel model again so that I can create any elements on the page that use these objects (genres, artists, etc.). The problem is that it requires me to copy and paste some code from ActionResult to ActionResult, which apparently makes my code not very dry.

Is there a better way to avoid repeated code? At the moment, I just moved the generation of any default objects that are required in the viewmodel to a separate method and / or constructor, but this is a bit messy, since I have to generate all the objects that may be needed for the entire controller. What I was hoping I could do was to point my second index action to the first index action and just use it as a regular method. I tried several different ways to do this, although I cannot return an ActionResult to another ActionResult.

Any thoughts?

+4
source share
2 answers

You can return another ActionResult method as follows:

 [HttpPost] public ActionResult Index(MusicViewModel musicViewModel) { if(ModelState.IsValid) { //Do some actions based on the user submitting a form } return MyAction(); } 

or you can pass the published model back to ViewResult

 [HttpPost] public ActionResult Index(MusicViewModel musicViewModel) { if(ModelState.IsValid) { //Do some actions based on the user submitting a form } return View(musicViewModel); } 

The second approach is better since you are not rebuilding the ViewModel

+4
source

I would suggest applying the Post / Redirect / Get pattern. It is great for MVC web applications.

Check this answer for sample code: ModelState.IsValid or Model.IsValid?

+6
source

Source: https://habr.com/ru/post/1340396/


All Articles