2011-11-26 63 views
0

我在ASP.NET應用程序中的搜索方法中收到Visual Studio 2010中的「無法訪問的代碼」消息。 這是方法:在ASP.NET應用程序中檢測到無法訪問的代碼

public ActionResult SearchIndex(string artist, string albumGenre, string searchString) 
    { 
     var GenreList = new List<string>(); 

     var GenreQuery = from d in storeDB.Albums orderby d.Genre.Name select   d.Genre.Name; 
     GenreList.AddRange(GenreQuery.Distinct()); 
     ViewBag.albumGenre = new SelectList(GenreList); 

     var ArtistList = new List<string>(); 

     var ArtistQuery = from a in storeDB.Artists orderby a.Name select a.Name; 
     ArtistList.AddRange(ArtistQuery.Distinct()); 
     ViewBag.artist = new SelectList(ArtistList); 

     var albums = from m in storeDB.Albums select m; 

     if (string.IsNullOrEmpty(artist)) 
     { 
      return View(albums); 
     } 
     else 
     { 
      return View(albums.Where(f => f.Artist.Name == artist)); 
     } 

     if (!String.IsNullOrEmpty(searchString)) 
     { 
      return View(albums.Where(s => s.Title.Contains(searchString))); 
     } 

     if (string.IsNullOrEmpty(albumGenre)) 
     { 
      return View(albums); 
     } 
     else 
     { 
      return View(albums.Where(x => x.Genre.Name == albumGenre)); 
     } 
    } 

對於這一說法I'getting消息:

 if (!String.IsNullOrEmpty(searchString)) 
     { 
      return View(albums.Where(s => s.Title.Contains(searchString))); 
     } 

我要去哪裏錯了嗎?

回答

0

以下是更正代碼

public ActionResult SearchIndex(string artist, string albumGenre, string searchString) 
    { 
     var GenreList = new List<string>(); 

     var GenreQuery = from d in storeDB.Albums orderby d.Genre.Name select   d.Genre.Name; 
     GenreList.AddRange(GenreQuery.Distinct()); 
     ViewBag.albumGenre = new SelectList(GenreList); 

     var ArtistList = new List<string>(); 

     var ArtistQuery = from a in storeDB.Artists orderby a.Name select a.Name; 
     ArtistList.AddRange(ArtistQuery.Distinct()); 
     ViewBag.artist = new SelectList(ArtistList); 

     var albums = from m in storeDB.Albums select m; 

     if (!string.IsNullOrEmpty(artist)) 
     { 
      return View(albums.Where(f => f.Artist.Name == artist)); 
     } 
     else if (!String.IsNullOrEmpty(searchString)) 
     { 
      return View(albums.Where(s => s.Title.Contains(searchString))); 
     } 
     else if (!string.IsNullOrEmpty(albumGenre)) 
     { 
      return View(albums.Where(x => x.Genre.Name == albumGenre)); 
     } 
     else 
     { 
      return View(albums); 
     } 

} 
+0

非常感謝。問題已經解決了 ;)。 –

1

之前的if在它的兩個分支中都有一個return語句,所以您的函數在到達第二個if之前總會返回。

2

因爲在之前的if-else塊中,您肯定會返回並放棄您的方法,無論是從if還是從else塊。

因此,您的以下代碼在任何情況下都不會執行。

相關問題