我尝试使用 !Model.Any() 它不起作用,因为模型没有扩展名 Any。怎么解决? 这是我的代码片段。
@model MyModel.Work
@if ( !Model.Any() )
{
<script type="text/javascript">
alert("Model empty");
</script>
}
else
{
<script type="text/javascript">
alert("Model exists");
</script>
}
最佳答案
在我看来,您正在实例化模型,但想检查它是否已填充。
我执行此操作的标准方法是创建一个名为 Empty
的 bool
属性,仅给出 get,然后返回您需要的检查以查看是否没有其他属性已设置。
假设您有一个 Customer 类作为模型:
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));
}
}
}
现在在您的模型中,您只需调用:
@model MyModel.Work
@if (Model.Empty)
{
<script type="text/javascript">
alert("Model empty");
</script>
}
else
{
<script type="text/javascript">
alert("Model exists");
</script>
}
关于asp.net-mvc-3 - MVC3 Razor : how to check if model is empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448778/