MVC3 Razor: how to check if model is empty
how about this:
if(Model == null)
{
}
It sounds to me like you are instantiating the model, but want to check and see if it's been populated.
My standard way of doing this is to create a bool
property called Empty
, only giving a get, and then return the check you need to see if no other properties have been set.
Say you have a Customer class as your model:
public class Customer
{
public int CustomerId {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public string Email {get;set;}
public bool Empty
{
get { return (CustomerId == 0 &&
string.IsNullOrWhiteSpace(FirstName) &&
string.IsNullOrWhiteSpace(LastName) &&
string.IsNullOrWhiteSpace(Email));
}
}
}
Now in your model, you simply call:
@model MyModel.Work
@if (Model.Empty)
{
<script type="text/javascript">
alert("Model empty");
</script>
}
else
{
<script type="text/javascript">
alert("Model exists");
</script>
}
You can try this:
@if (Model.Count == 0)
{
}