是否有更好的方法来编写检查嵌套对象是否为空的 razor cshtml 代码,这样如果容器为空,它就不会在容器对象上抛出空异常错误。例如:
page.cshtml
Hello @obj1.obj2.prop3
如果 obj1 为 null 或 obj1.prop3 为 null 将抛出错误,但是
Hello @Html.DisplayFor(m => obj1.obj2.prop3)
可以在 obj1 或 obj1.obj2 上检查 null,这样它就不会抛出错误
Hello @(obj1 == null? "" : (obj1.obj2 == null? "" : obj1.obj2.prop3))
太长了
最佳答案
您可以尝试创建自己的 html 助手:
static class MyOwnHtmlHelpers
{
public static string EmptyIfNull<TModel>(this HtmlHelper<TModel> helper, Func<TModel, string> accessor)
{
try
{
var result = accessor.Invoke(helper.ViewData.Model);
return result;
}
catch(NullReferenceException)
{
return string.Empty;
}
}
}
然后像这样使用它:
@Html.EmptyIfNull(m => obj1.obj2.prop3)
关于c# - 在 Razor 中检查 null 的语法糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14975202/