2012-12-20 17 views
6

Ho un ActionResult che chiama un altro ActionResult.MVC ActionResult chiama un altro ActionResult

Ho una chiamata a un ActionResult nella dichiarazione del mio caso che non funziona. Ecco quello che ho:

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

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

     return actionResult; 
     } 

ottengo il seguente errore: 'ActionResult' non esiste nel contesto attuale

Se faccio la seguente funziona ma non del tutto quello che mi serve:

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; 
     } 

Come faccio ad avere l'ActionResult a lavorare nel mio caso tale affermazione che è visibile quando faccio

return actionResult 
+0

hai considerato 'RedirectToAction'? – MilkyWayJoe

risposta

8

Basta dichiarare per primo (con un valore di default, credo), al di fuori dell'istruzione switch:

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

return actionResult ?? new View(); 

Nota: ho aggiunto la ?? new View() come valore di default, nel caso in cui nessuno dei casi assegnare nulla a actionResult - modificare questo se necessario.

+2

L'assegnazione a null è ridondante. – Kugel

+4

@Kugel no non lo è, devi assegnargli qualcosa, o ottieni un 'uso di variabile locale non assegnata "actionResult" 'errore del compilatore. – McGarnagle

+1

@Kugel beh, per essere precisi, * potrebbe * lasciarlo indefinito se * ogni * caso assegna qualcosa ad esso, ma non è questo il caso presentato dall'Op. – McGarnagle

0

Il problema è ambito variabile. dbaseman ha quasi avuto ragione ... fai questo:

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; 
} 
+1

È necessario dichiarare 'actionResult = null' o si otterrà un' uso di variabile locale non assegnata "actionResult" 'errore del compilatore. –

Problemi correlati