简体   繁体   English

具有空值的ASP.Net MVC3 Razor模板变量

[英]ASP.Net MVC3 Razor Template Variables with null value

I have been developing Castle Monorail MVC web applications for a while. 我一直在开发Castle Monorail MVC Web应用程序。 I started to learn and develop some projects with Asp.Net MVC 3 and Razor. 我开始用Asp.Net MVC 3和Razor学习和开发一些项目。

I was using NVelocity as Monorail's view engine. 我使用NVelocity作为Monorail的视图引擎。 It has capability to use variables passed with PropertyBag, like $!variablename . 它有能力使用通过PropertyBag传递的变量,如$!variablename That allows me to use as, if variable is equal to null, then it doesn't print any value and throws no exception. 这允许我使用as,如果变量等于null,那么它不会打印任何值并且不会抛出任何异常。

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? 有没有像这样的MVC 3使用的方法,或者我总是要检查ViewData传递的变量是否为空?

Thanks in advance. 提前致谢。

If you use ViewBag or ViewData to pass a string, you don't have to check for nullity. 如果使用ViewBagViewData传递字符串,则不必检查是否为null。

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. 如果要传递更复杂的对象,例如具有属性NameUserObject ,则尝试访问@ViewBag.UserObject.Name将导致错误。 In this case, you should check for nullity, something like: 在这种情况下,您应该检查无效,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM