如何检查MVC 3视图的模型是否包含某些数据?

时间:2011-03-20 17:25:23

标签: asp.net-mvc asp.net-mvc-3 webgrid

我的观点是使用WebGrid显示网格。

如果模型有一些数据,但是如果模型没有数据,则WebGrid会给出异常,但效果很好。

我尝试检查Model != null是否只是让我的代码在IF中执行。还尝试进行检查以查看if (Model.Count() > 2),这只是给了我一条消息"The specified resource does not exist."

使用这两个条件中的任何一个执行IF内部的代码。有没有一种简单的方法可以检查传入的信息以查看模型是否有任何行?

@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);

3 个答案:

答案 0 :(得分:2)

您可以发送列表操作emmty list example:

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

答案 1 :(得分:1)

  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();
     }
  }

答案 2 :(得分:1)

当模型没有任何数据时,这就是我用webgrid处理一个scenaro的方式。

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

     <div id="grid">


        @grid.GetHtml()

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