How to check null value in MVC view?

I am using MVC with the LINQ-to-SQL class.

since the foreign key can be null, I have one entry that has fk null and the others have values.

I now show it in the Index view.

In the index view, I enable fk by writing code like

<%= Html.Encode(item.UserModified.UserName) %> 

Now I have a problem in that "the reference to the object is not installed."

And this is because we have a zero value in one of the fk field!

so I can write code to check if the related object points to zero or nothing?

+4
source share
3 answers

If necessary, you can write any code you want in the view so that you can:

 <%= Html.Encode(item.UserModified.UserName ?? string.Empty) %> 

You can also do the HtmlHelper extension for this:

 public string SafeEncode(this HtmlHelper helper, string valueToEncode) { return helper.Encode(valueToEncode ?? string.Empty); } 

You could just do:

 <%= Html.SafeEncode(item.UserModified.UserName) %> 

Of course, if it is UserModified null, not UserName, then you will need different logic.

+5
source

With C #, you can use the conditional operator:

 <%= Html.Encode(item.UserModified == null ? "" : item.UserModified.UserName) %> 

However, it might be better to choose the UserName property to be a direct child of the element or placed in the ViewData.

+1
source

First, consider if your model really has an instance of a user without a name. If not, then you should put a guard clause in the constructor.

Secondly, too many duplicate null checks are the smell of code. You must use 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 need to check Null everywhere.

0
source

All Articles