Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an ActionResult from another ActionResult

Say I have the following code, mocked up in notepad, so excuse any minor errors :)

//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 point of concern is that in order to postback any errors with the ModelState being invalid, I need to generate the viewmodel again so that any elements on the page that use those objects can be created (genres, artists etc.). The problem is it requires me copying and pasting some of the code from ActionResult to ActionResult, seemingly making my code not very DRY.

Is there a better way of avoiding repeated code like this? At the moment I have simply moved the generation of any default objects the viewmodel needs into a separate method and/or the constructor, but it's a bit messy since I have to generate all the objects I might need for the entire controller. What I was hoping I could do would be to point my second Index Action to the first Index Action and just use that as a regular method. I've tried a few different ways of doing this though and cant seem to return an ActionResult into another ActionResult.

Any thoughts?

like image 504
boolean Avatar asked Dec 28 '22 01:12

boolean


1 Answers

I would suggest applying Post/Redirect/Get pattern. It's perfectly suited for MVC web apps.

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

like image 156
Jakub Konecki Avatar answered Jan 18 '23 02:01

Jakub Konecki