开发者

How can I check if an MVC 3 view's model has some data?

My view is using WebGrid to display a grid.

It works good if the Model has some data but if the model comes with no data then the WebGrid gives and exception.

I tried doing a check if Model != null but that just let my code within the IF execute. Also tried doing a check to see if (Model.Count() > 2) and that just gave me a message saying "The specified resource does not exist.".

With either of those开发者_C百科 two conditions the code inside of the IF executed. Is there a simple way that I can check the information being passed in to see if the Model has any rows?

@model IEnumerable<Selftestware.Storage.Models.TestFormat>

@section content {
    <div id="content">

    @if (    Model  != null) { 

        var grid = new WebGrid(
             source: Model,
             defaultSort: "Name", 
             canPage: true, 
             canSort: true,
             rowsPerPage: 20);


You can send in List action emmty list example:

public ActionResult List()
{
//hear check if is null 
return View(new List<yourModel>());
}


  public static class YourWelcome{
     public static bool IsNullOrHasNullProperties(this object model){
         if(model == null) { 
             return true;
         }
         return model.GetType()
              .GetProperties(BindingFlags.Public|BindingFlags.Instance)
              .Where(propertyInfo => !propertyInfo.PropertyType.IsValueType)
              .Any(propertyInfo => propertyInfo.GetValue(model,null) == null);
     }
     public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable){
         return enumerable == null || !enumerable.Any();
     }
  }


This is how I handled a scenaro with my webgrid when the model did not have any data.

if (Model.Results.Count() > 0)
 {

     <div id="grid">


        @grid.GetHtml()

     </div> 
}
else
{
    <p>No Results Found.</p>
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜