ASP.Net MVC3 Razor Template Variables with null value

1k views Asked by At

I have been developing Castle Monorail MVC web applications for a while. I started to learn and develop some projects with Asp.Net MVC 3 and Razor.

I was using NVelocity as Monorail's view engine. It has capability to use variables passed with PropertyBag, like $!variablename. That allows me to use as, if variable is equal to null, then it doesn't print any value and throws no exception.

Is there any approach to be used with MVC 3 like that or do I always have to check if passed variables with ViewData is null or not?

Thanks in advance.

1

There are 1 answers

1
Lucas Reis On BEST ANSWER

If you use ViewBag or ViewData to pass a string, you don't have to check for nullity.

If you are passing a more complex object, say a UserObject with a property Name, then trying to access @ViewBag.UserObject.Name will cause an error. In this case, you should check for nullity, something like:

@if (ViewBag.UserObject != null) { ViewBag.UserObject.Name }