Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a variable exists in MVC3 razor layout?

I'm just digging in to .NET views with the razor syntax. Most of my coding knowledge is in javascript so this is probably a basic question (or my approach is completely wrong!). In my html, I am building dns prefetch tags based on an array declared at the top of template. Maybe I am approaching this wrong because of my javascript background, but if one of my views doesn't need any pre-fetch tags, I'd like to avoid declaring the DNSPrefetch variable.

How can I test if a variable exists, and then execute some code based on the result? I got it to work using a try/catch, but was thinking that there is a better way. Thanks!

In _Layout (working with try/catch):

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

In template:

  @{
    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;
}
like image 620
ErikPhipps Avatar asked Dec 20 '22 17:12

ErikPhipps


1 Answers

You can just check if the value is null:

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

(Alternatively, you could declare DNSArray as an empty array when it's not needed, then you could use the foreach block as-is for all cases.)

like image 157
McGarnagle Avatar answered Jan 10 '23 21:01

McGarnagle