Gordon Howe
Gordon Howe

Reputation: 1

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

Upvotes: 0

Views: 9509

Answers (3)

KeelRisk
KeelRisk

Reputation: 749

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

Upvotes: 1

smartcaveman
smartcaveman

Reputation: 42256

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

Upvotes: 1

Florim Maxhuni
Florim Maxhuni

Reputation: 1421

You can send in List action emmty list example:

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

Upvotes: 2

Related Questions