Reputation: 24322
I am using MVC with LINQ-to-SQL class.
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.
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".
And this is because of we are having null value in one of the f.k. field!
so can i write code in view to check whether Associated object pointing to null or nothing?
Upvotes: 4
Views: 11308
Reputation: 9312
First consider whether in your model an instance of User is valid without Name. If no then you should put a guard clause in the constructor.
Secondly, too many and duplicated null checks is a code smell. You should use the refactoring Replace Conditional with Polymorphism. You can create a Null object according to the Null Object Pattern.
This will make sure that you do not have to check for Null everywhere.
Upvotes: 0
Reputation: 11608
You can write any code you want in the view if necessary, so you could do:
<%= Html.Encode(item.UserModified.UserName ?? string.Empty) %>
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) %>
Of course if it's UserModified that's null and not UserName then you'll need some different logic.
Upvotes: 5
Reputation: 8266
With C#, you can use the conditional operator:
<%= Html.Encode(item.UserModified == null ? "" : item.UserModified.UserName) %>
However, it might be a better choice to move the UserName property to be a direct child of item, or to put it in ViewData.
Upvotes: 1