jaffa
jaffa

Reputation: 27350

How do I render a enum value check against a enum type in Razor

I would like to know how to achieve this in Razor.

At the moment I have this inside some JavaScript:

if (@Convert.ToInt16(ViewBag.Status.Type) == @Convert.ToInt16(StatusType.Info))
{
   // do something here
}

But I'm wondering if there is a better way? Seems a bit of a cludgy way of doing it...

Upvotes: 1

Views: 3623

Answers (1)

Nick Craver
Nick Craver

Reputation: 630389

There are a few options here, what I tend to go with is not rendering the JavaScript at all unless the if() matched (it's a hunk of unused code in that case, right?), like this:

@if ((int)ViewBag.Status.Type == (int)StatusType.Info)
{
   @:document.getElementById('test')...
}

Or for larger blocks, <text> for example:

@if ((int)ViewBag.Status.Type == (int)StatusType.Info)
{
   <text>
   var elem = document.getElementById('test');
   elem.focus();
   </text>
}

Upvotes: 2

Related Questions