2016-04-24 6 views
3

Ich möchte eine Ansicht zurückgeben, wenn ein Objekt (Land) nicht null ist. Aber ich erhalte die Fehlermeldung „Nicht alle Codepfade einen Wert zurückgeben“"Nicht alle Codepfade geben einen Wert zurück" beim Zurückgeben der Ansicht in MVC

Mein Code sieht wie folgt aus

public ActionResult Show(int id) 
{ 
    if (id != null) 
    { 
     var CountryId = new SqlParameter("@CountryId", id); 
     Country country = MyRepository.Get<Country>("Select * from country where [email protected]", CountryId); 
     if (country != null) 
     { 
      return View(country); 
     } 
    } 

} 

Antwort

5

Dies geschieht, wenn Sie etwas aus dem „if“ Anweisung zurückkehren. Der Compiler denkt, was ist, wenn die "if" Bedingung falsch ist? Auf diese Weise geben Sie nichts zurück, selbst wenn Sie den Rückgabetyp "ActionResult" in der Funktion definiert haben. Fügen Sie daher einige Standardretouren in der else-Anweisung hinzu:

public ActionResult Show(int id) 
{ 

    if (id != null) 
    { 
     var CountryId = new SqlParameter("@CountryId", id); 
     Country country = MyRepository.Get<Country>("Select * from country where [email protected]", CountryId); 

     if (country != null) 
     { 
      return View(country); 
     } 
     else 
     { 
      return View(something); 
     } 
    } 
    else 
    { 
     return View(something); 
    } 
} 
Verwandte Themen