Nate Pet
Nate Pet

Reputation: 46222

MVC ActionResult calling another ActionResult

I have an ActionResult calling another ActionResult.

I have a call to an ActionResult in my case statement which doesn't work. Here is what I have:

   public ActionResult GetReport(string pNum)
   {
   ....

        switch (methodId)
        {
          case 1:
          case 5:                
           {
             var actionResult =  GetP1Report("33996",false)  as ActionResult;
              break;
           }
         }

         return actionResult; 
       }

I get the following error: 'actionResult' does not exist in the current context

If I do the following it works but not quite what I need:

    public ActionResult GetReport(string pNum)
   {
      ....

       var actionResult =  GetP1Report("33996",false)  as ActionResult;

        switch (methodId)
        {
          case 1:
          case 5:                
           {
             // var actionResult =  GetP1Report("33996",false)  as ActionResult;
              break;
           }
         }

         return actionResult; 
       }

How do I get the actionResult to work in my case statement such that it is visible when I do

    return actionResult

Upvotes: 6

Views: 8991

Answers (2)

Serj Sagan
Serj Sagan

Reputation: 30208

The problem is variable scope. dbaseman almost had it right... do this:

public ActionResult GetReport(string pNum)
{
....

    ActionResult actionResult = new View(); // This would typically be assigned a
                                        // default ActionResult
    switch (methodId)
    {
        case 1:
        case 5:                
        {
            actionResult = GetP1Report("33996",false) as ActionResult;
            break;
         }
     }

     return actionResult; 
 }

Upvotes: 0

McGarnagle
McGarnagle

Reputation: 102753

Just declare it first (with a default value, I guess), outside of the switch statement:

 ActionResult actionResult = null;
 switch (methodId)
    {
      case 1:
      case 5: // PVT, PVT-WMT
      {
          actionResult =  GetP1Report("33996",false)  as ActionResult;
          break;
       }
     }

 return actionResult ?? new View(); 

Note: I added the ?? new View() as a default value, in case none of the cases assign anything to actionResult -- modify this as needed.

Upvotes: 8

Related Questions