Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: How to render a different action (not view) with the model?

It's really easy to return a different View from the Controller:

return View("../Home/Info");

However, I need a model in the Info view. I have a lot of stuff going on in the Info() action result method. I can just copy it and have something like this:

var infoModel = new InfoModel {
    // ... a lot of copied code here
}
return View("../Home/Info", infoModel);

But that is not reasonable.

Of course I can just redirect:

return RedirecToAction("Info");

But this way the URL will change. I don't want to change the URL. That's very important.

like image 478
Alex Avatar asked Dec 02 '22 00:12

Alex


2 Answers

You can call right to another action from within an action, like this:

public ActionResult MyAction(){
   if(somethingOrAnother){
      return MyOtherAction();
   }
   return View();
}

//"WhichEverViewYouNeed" is required here since you are returning this view from another action
//if you don't specify it, it would return the original action's view
public ActionResult MyOtherAction(){
    return View("WhichEverViewYouNeed", new InfoModel{...});
}
like image 97
Andrew Barber Avatar answered Dec 18 '22 21:12

Andrew Barber


It looks like you want to invoke an action from a different controller. I'd suggest that you might want to simply render a view that renders that action using Html.Action() instead of trying to tie the two together in the controller. If that's unreasonable then you might want to create a base controller that both controllers can derive from and put the shared code to generate the model in base controller. Reuse the view as needed.

  public ActionResult Foo()
  {
      return View();
  }

Foo View

  @Html.Action( "info", "home" ) 
like image 35
tvanfosson Avatar answered Dec 18 '22 23:12

tvanfosson