我想设计我的自定义编辑器模板,以便它们即使在传递空模型时也能正常工作。即,当 Model
为 null 时,@Html.EditorForModel()
。
我遇到的问题是,当我在 EditorTemplate 中时,我有时需要访问模型的属性之一,而编写 @if(Model != null && Model.[Property ] ...)
例如
@model MyObject
@if(Model.BoolProperty) // throws NullReferenceException
{
<div>...additional stuff here</div>
}
@Html.EditorFor(m => m.OtherProperty)
我考虑添加如下扩展方法
public static R GetValue<T, R>(this WebViewPage<T> viewPage, Func<T, R> selector)
{
if (selector == null) throw new ArgumentNullException("selector");
if (viewPage == null) throw new ArgumentNullException("viewPage");
if (viewPage.Model == null) return default(R);
return selector(viewPage.Model);
}
并在 EditorTemplate 中使用它,如下所示
@model MyObject
@if(this.GetValue(m => m.BoolProperty)) // Safely gets value or false
{
<div>...additional stuff here</div>
}
@Html.EditorFor(m => m.OtherProperty)
但是我想知道是否有内置或“正确”的方式来尝试访问这些属性(如果模型存在),而不抛出NullReferenceException
。
最佳答案
为什么不检查一次:
@model MyObject
@if (Model == null)
{
<div>Sorry, nothing to edit here<div>
}
else
{
... here you can access the model properties
}
甚至在调用模板时在外部:
@if (Model != null)
{
@Html.EditorForModel()
}
这样在模板中您不再需要检查模型是否为空。
关于asp.net-mvc - 是否有正确的方法来检查 EditorTemplate 中模型的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10217903/