1

I have two ASP.NET MVC Actions:

public ActionResult GetAll()
{
      return GetOne(1);
}

public ActionResult GetOne(Int32 id)
{
      return View(id);
}

As you can see, GetAll is calling the action GetOne. However, when GetAll() is called (calling GetOne(id) and should be returning GetOne view) MVC throws an error saying that there is no GetAll view. Huh?

How can I have GetAll call GetOne and use GetOne's view (which I thought was the logical thing to happen to begin with)?

Alex
  • 75,813
  • 86
  • 255
  • 348

2 Answers2

6
public ActionResult GetOne(Int32 id)
{
      return View(id, "GetOne");
}

Specifying the view name explicitly overrides the default, which is to use the action key in the route values collection, which is equal to "GetAll" in this case.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • @Craig, Thanks for the answer! Do you consider it a normal practice to call actions within other actions? In my opinion one action should be independent from another action. This way they can easily be tested and used. – azamsharp Sep 16 '09 at 20:39
  • It is important to avoid duplication of code at all costs. There are many ways to do this, though. You could have two "independent" actions which call a shared function go get a model, e.g. In this case it seems clear that the same view should be used. So the view must be either specified explicitly or a shared view of some type (like MVC 2 default templated views) could be used. In other words, it depends on what you're doing. – Craig Stuntz Sep 16 '09 at 20:53
1

ASP.NET MVC, like many MVC frameworks, makes a lot of assumptions based on convention. If you don't follow their convention, you'll have a little more work to do. In this case, the convention is that their is a view with the same name as your action, in the folder that corresponds to the name of your controller.

If you controller is UsersController, and your action is GetAll, it expects to find a view Views/Users/GetAll.

If you want to return a view that corresponds with a different action, you need to specify that (instead of using the default):

return View(id, "GetOne")
Matt
  • 41,216
  • 30
  • 109
  • 147
  • But I am calling the Action GetOne (whose view exists)?? The only difference is that I call it from another action. – Alex Sep 17 '09 at 08:17