如何测试MVC3剃刀布局中是否存在变量?

Eri*_*pps 4 asp.net-mvc razor

我只是用剃刀语法挖掘.NET视图.我的大多数编码知识都是用javascript编写的,所以这可能是一个基本问题(或者我的方法完全错误!).在我的html中,我正在根据模板顶部声明的数组构建dns预取标记.也许我因为我的javascript背景而接近这个错误,但是如果我的一个视图不需要任何预取标记,我想避免声明DNSPrefetch变量.

如何测试变量是否存在,然后根据结果执行一些代码?我使用try/catch让它工作,但我认为有更好的方法.谢谢!

在_Layout中(使用try/catch):

  @{
    try {
      foreach (var dns in ViewBag.DNSPrefetch) {
        <link rel="dns-prefetch" href="//@dns" />
      }
    }
    catch{}
  }
Run Code Online (Sandbox Code Playgroud)

在模板中:

  @{
    Layout = "~/Views/Shared/_Layout.cshtml";

    // DNS prefetching for improved performance. More reading: http://html5boilerplate.com/docs/DNS-Prefetching/
    string[] DNSArray = { "ajax.googleapis.com", "mpsnare.iesnare.com" };
    ViewBag.DNSPrefetch = DNSArray;
}
Run Code Online (Sandbox Code Playgroud)

McG*_*gle 8

您可以检查值是否为null:

@{
  if (ViewBag.DNSPrefetch != null) {
    foreach (var dns in ViewBag.DNSPrefetch) {
      <link rel="dns-prefetch" href="//@dns" />
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

(或者,您可以在不需要时将DNSArray声明为空数组,然后您可以按原样使用foreach块.)