asp.net mvc - Returning an ActionResult from another ActionResult -
say have following code, mocked in notepad, excuse 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 example, pretend have class called musicstoresubmission in //viewmodel holds few different fields user fills out. if(modelstate.isvalid) { //do actions based on user submitting form } //else, refresh page errors in modelstate. var musicviewmodel { albums = gettopsellingalbums(5), genres = gettopgenres(5), artists = gettopartists(5) }; return view(musicviewmodel); }
my point of concern in order postback errors modelstate being invalid, need generate viewmodel again elements on page use objects can created (genres, artists etc.). problem requires me copying , pasting of code actionresult actionresult, seemingly making code not dry.
is there better way of avoiding repeated code this? @ moment have moved generation of default objects viewmodel needs separate method and/or constructor, it's bit messy since have generate objects might need entire controller. hoping point second index action first index action , use regular method. i've tried few different ways of doing though , cant seem return actionresult actionresult.
any thoughts?
you can return actionresult method this:
[httppost] public actionresult index(musicviewmodel musicviewmodel) { if(modelstate.isvalid) { //do actions based on user submitting form } return myaction(); }
or pass posted model viewresult
[httppost] public actionresult index(musicviewmodel musicviewmodel) { if(modelstate.isvalid) { //do actions based on user submitting form } return view(musicviewmodel); }
the second approach better don't rebuild viewmodel
Comments
Post a Comment