更新
问题是语法问题。 @awrigley 展示了在 Razor 中编写它的正确方法。
以下工作:
@if(Model.Thing.Prop != null)
{
Html.RenderPartial("SomePartialView", Model.Thing.Prop);
}
您需要显示前 1
Foo
的详细信息对于给定的 Bar
作为 HTML 表格。如果Foo
,您如何隐藏空表或显示“未找到”消息一片空白?例如。我收到了
NullReferenceException
在下一行,因为 Model.Thing.Prop
是 null
;@{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
它故意为空,我的存储库返回空而不是空
Foo
.但这有点离题,即给定一个 null Model.Thing.Prop
,我不想调用Html.RenderPartial
.更新
我试过以下没有运气:
@if(Model.Thing.Prop != null)
{
@{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
}
这导致 Visual Studio 告诉我它正在等待
;
在第 1 行,第 1 列以及 ;
是第 1 行第 1 列的无效表达式(我猜这是由于 MVC3 的预发布状态),如果我在浏览器中点击页面,我会得到CS1501: No overload for method 'Write' takes 0 arguments
与
@Html.RenderPartial
行突出显示。我也试过
@if(Model.Thing.Prop != null)
{
<text>
@{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
</text>
}
但这会导致
NullReferenceException
从我的部分 View 中,这似乎不正确。 Model.Thing
绝对是有效的 Bar
和 Model.Thing.Prop
绝对是null
Foo
.
最佳答案
我想你不想使用...
@if (Model.Thing.Prop != null)
{Html.RenderPartial("SomePartialView", Model.Thing.Prop);}
...因为您仍然想渲染部分 View 的一部分?
不好了。已正确阅读您的帖子。
我不知道为什么上面的代码对你不起作用。
编辑:
请记住,在 Razor 中,@ 可以通过两种方式使用:
@{
我的声明;
}
@MyClass.MyStringProperty
请注意,在情况 2 中,不需要终止分号。
1 和 2 表示如果您有一个 htmlhelper 返回字符串以外的内容(例如,void),那么您必须按如下方式调用它:
@{Html.MyHelperThatReturnsVoid;}
而对于返回字符串或 HtmlString 或 MvcHtmlString 的 HtmlHelper,您可以简单地编写:
@Html.MyHelperThatReturnsAString
有关更多详细信息,请参阅 接受的答案 我问的一个问题:
Custom HtmlHelper that returns void problem
关于asp.net-mvc - 在 ASP.NET MVC 中防止 NullReferenceException 的正确模式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4261754/