Reputation: 315
I have a ViewModel with two Models in it. In the View I want to see if there is any data in the Model:
@if (Model.MyModel1 == Empty) { do something }
But I can not figure out how to do this. When I remove this check the View works fine, I can display data from the models (when there is data) with no issues. I spent yesterday and half a day today trying a lot of different approaches I found on the web but none of them worked and none of them talked about ViewModels, only single Models, so I wonder if that is my issue. I have tried:
Model.MyModel1.Any()
Model.MyModel1.AsQueryable().Any()
Model.MyModel1[0].value1 == ""
Model.MyModel1 == null
Model.MyModel1.IsEmptyOrNull()
More and more along these lines..
I get two types of errors, the first is when I try using a function like Model.MyModel1.Any()
I get:
RuntimeBinderException: 'System.Linq.EnumerableQuery<MyThing.Models.MyModel1>' does not contain a definition for 'Any'
When I try something like Model.MyModel1[0].value1 == null
I get:
RuntimeBinderException: Cannot apply indexing with [] to an expression of type 'System.Linq.EnumerableQuery<MyThing.Models.MyModle1>'
The ViewModel is:
namespace MyThing.ViewModel
{
public class combinedModel
{
public IQueryable<MyModel1> MyModel1{ get; set; }
public IQueryable<MyModel2> MyModel1{ get; set; }
}
}
When there is no data the Controller uses this code:
var combinedModel = new combinedModel();
combinedModel.MyModel1 = Enumerable.Empty<MyModel1>().AsQueryable();
combinedModel.MyModel2 = Enumerable.Empty<MyModel2>().AsQueryable();
return View(combinedModel);
Upvotes: 0
Views: 215
Reputation: 315
For my situation it seems that, as Xiaoy312 pointed out, I can not use Extension Methods in my View for some unknown reason. While I believe his answer is correct (and may be preferred way) to do this it did not work for me so I am posting what did work in case anyone else has the same issue with Extension Methods. I would read Xiaoy312 answer and comments before trying this approach.
To check if there is data in your Model, without using Extension Methods in your View, you can use:
(Queryable.Count(Model.MyModel1) < 1 )
Upvotes: 0
Reputation: 14477
You were close with your first try, Model.MyModel1.Any()
. However, it tests if the sequence has any element, so you want to negate that result to know if it is empty or not.
@if (!Model.MyModel1.Any()) { do something }
Upvotes: 1