c# - How to hide @Html.DropDownList if ViewBag is null or empty -


i have @html.dropdownlist take data controller in edit mode. need hide dropdown element , show message if list null or empty.

i try code in view, time give me result thet have, , show empty dropdown:

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

and code controller here:

viewbag.datumrid = new selectlist(db.tbl_relacii.where(x => x.datumr == tbl_rezervacii.datump).orderby(x => x.datumr), "relid", "datumfordisplay", tbl_rezervacii.datumrid); 

when record fount dropdown ok, when record null dropdown show empty.

check list size also. correct displaying data selectlist must contain more 0 items. try this:

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

update: u may try update controller code this:

    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; 

and pass "viewlist" object dropdownlist helper @ razor markup.


Comments