如何检查MVC中的视图空值? [英] How to check null value in MVC view?
问题描述
我使用MVC与LINQ到SQL类。
I am using MVC with LINQ-to-SQL class.
为外键可以为空,我有F.K.有一个记录空和其他人有价值观。
as foreign key can be null, i have one record having f.k. null and others are having values.
现在我有鉴于索引视图显示它。
now i am displaying it in view by Index view.
在索引视图我正在解决F.K.通过写code像
In index view i am resolving f.k. by writing code like
<%= Html.Encode(item.UserModified.UserName) %>
现在我有一个问题的观点,即对象引用未设置。
Now i have a problem in view that "object reference is not set".
这是因为我们在F.K.的一种具有null值现场!
And this is because of we are having null value in one of the f.k. field!
所以我写鉴于code,检查关联对象是否指向空或没有?
so can i write code in view to check whether Associated object pointing to null or nothing?
推荐答案
您可以写任何code你想在视图如果需要的话,那么你可以这样做:
You can write any code you want in the view if necessary, so you could do:
<%= Html.Encode(item.UserModified.UserName ?? string.Empty) %>
您也可以做一个扩展的HtmlHelper做到这一点:
You could also make a HtmlHelper extension to do this:
public string SafeEncode(this HtmlHelper helper, string valueToEncode)
{
return helper.Encode(valueToEncode ?? string.Empty);
}
那么你可以简单地做:
You could then simply do:
<%= Html.SafeEncode(item.UserModified.UserName) %>
当然,如果是UserModified这是空,然后没有用户名,你就需要一些不同的逻辑。
Of course if it's UserModified that's null and not UserName then you'll need some different logic.
这篇关于如何检查MVC中的视图空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!