2017-04-05 64 views
-1

我有@ Html.DropDownList從控制器在編輯模式下的數據。我需要隱藏DropDown元素,並顯示一些消息,如果列表爲空或空。如何隱藏@ Html.DropDownList如果ViewBag爲空或空

我嘗試用這個代碼視圖,但所有的時間給我造成泰德擁有,並顯示空的下拉菜單:

@if(ViewBag.DatumRID != null) 
       { 
        <div class="col-md-10"> 
         @Html.DropDownList("DatumRID", null, htmlAttributes: new { @class = "form-control" }) 
         @Html.ValidationMessageFor(model => model.DatumRID, "", new { @class = "text-danger" }) 
        </div> 
       } 
       else 
       { 
        <h6 style="color:#ff0000"> NO RECORDS.</h6> 
       } 

而且從控制器代碼是在這裏:

ViewBag.DatumRID = new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID); 

時記錄fount下拉菜單可以,但是當記錄爲空時,下拉列表顯示爲空。

+0

代替ViewBag.DatumRID使用模型:Model.DatumRID在模型上設置列表 –

+0

控制器中的代碼正在創建一個「SelectList」 - 它不能爲null,只是空的。 - 'var data = db.tbl_relacii.Where(....); if(data.Any()){ViewBag.DatumRID = new SelectList(...); }' –

+0

謝謝@Stephen Muecke它的工作。 –

回答

0

查看列表大小還。爲了正確顯示數據,SelectList必須包含多於零個項目。試試這個:

@if(ViewBag.DatumRID != null && ViewBag.DatumRID.Count > 0) 
{ 
     <div class="col-md-10"> 
      @Html.DropDownList("DatumRID", null, htmlAttributes: new { @class = "form-control" }) 
      @Html.ValidationMessageFor(model => model.DatumRID, "", new { @class = "text-danger" }) 
     </div> 
} 
else 
{ 
     <h6 style="color:#ff0000"> NO RECORDS.</h6> 
} 

更新: U可以嘗試更新你這樣的控制器代碼:

List<SelectListItem> viewList = new List<SelectListItem>(); 
    viewList.AddRange(new SelectList(db.tbl_relacii.Where(x => x.DatumR == tbl_rezervacii.DatumP).OrderBy(x => x.DatumR), "relID", "DatumForDisplay", tbl_rezervacii.DatumRID)); 
    ViewBag.DatumRID = viewList; 

又通 「Viewlist產品」 對象爲DropDownList助手在剃刀標記。

+0

我有這個錯誤**'System.Web.Mvc.SelectList'不包含'Count'的定義**在行:'@if(ViewBag.DatumRID!= null && ViewBag.DatumRID.Count> 0)' –