2014-02-21 34 views
0

我是MVC 4的初學者。我編寫代碼檢索數據並將數據填充到下拉列表中,該列表工作正常。但是,如果數據庫被破壞,數據不能被檢索,所以我希望下拉列表顯示空白或像「沒有數據」以一種很好的方式而不是拋出錯誤。我試圖使用ViewBag.NoData,但它不起作用。如何與我下面的代碼解決這個問題:mvc 4 - html.dropdownlist從數據庫檢索沒有數據,它應該返回空白,而不是拋出錯誤

HomeController的C#:

public ActionResult Index() 
    { 
     try 
     { 
      ViewBag.PersonList = Helper.LoadPersonData(); 

      if (ViewBag.PersonList == null) 
      { 
       ViewBag.NoPersonData = "NO DATA"; 
      } 
     } 
     catch (Exception ex) 
     { 
      TempData["Message"] = string.Format("An error occurred. Details: {0}", ex.Message); 
     } 

     return View(persons); 
    } 

Index.cshtml:

<td>@Html.DropDownList("txtPersonName",((IEnumerable<SelectListItem>)ViewBag.PersonList).Any() ?  new SelectList(ViewBag.PersonList as IEnumerable<SelectListItem>,"Value", "Text",selectedValue: Session["search"] != null ? (((SearchKey)Session["search"]).PersonName) : (string)ViewBag.NoPersonData): null, "---------SELECT---------")</td> 

回答

0

你可以只返回一個包含「無數據列表「entry:

public ActionResult Index() 
{ 
    try 
    { 
     ViewBag.PersonList = Helper.LoadPersonData(); 

     if (ViewBag.PersonList == null) 
     { 
      ViewBag.PersonList = new List<SelectListItem>() 
      { 
       new SelecListItem() 
       { 
         Value = "nodata", 
         Text = "No Data" 
       } 
      }; 
     } 
    } 
    catch (Exception ex) 
    { 
     TempData["Message"] = string.Format("An error occurred. Details: {0}", ex.Message); 
    } 

    return View(persons); 
} 
+0

謝謝但List 不具有值和文本屬性。 – user3281338

+0

@ user3281338,oops。固定。 –

+1

哇,它像炸彈一樣工作。非常非常感謝你 :) – user3281338

0

您的PersonList可能爲空。試試這個:

 if (ViewBag.PersonList == null) 
     { 
      ViewBag.PersonList = new List<SelectListItem>(); 
      ViewBag.NoPersonData = "NO DATA"; 
     } 
相關問題