4

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.