Simon
Simon

Reputation: 2116

is if statement in my razor the best way to go?

Say I have my view and am passing it someModel with a property of list<someObjects>.

If I have a div and only want to display it if the list has a count greater than 0, is an if statement the "industry standard" way of displaying this in amongst my razor?

Upvotes: 1

Views: 1302

Answers (4)

Amit
Amit

Reputation: 15387

You can write if condition inside razor view because

 The Razor syntax is a template markup syntax, based on the C# programming 
 language,that enables the programmer to use an HTML construction workflow. 
 Instead of using the ASP.NET .ASPX markup syntax with <%= %>/@ symbols to 
 indicate code blocks, Razor syntax starts code blocks with a @ character
 and does not require explicit closing of the code-block.

Upvotes: 1

StanK
StanK

Reputation: 4770

Using simple logic like if statements and loops in your views is fine and quite a common thing to do.

If you find yourself using any other logic, or find that the if statements and loops are nested several levels deep, this may be a sign that your view is doing to much, and you should consider moving some of this logic to your controller.

At the end if the day, the decision of where to draw the line is a personal thing, and there is no 'industry standard'.

Upvotes: 1

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93434

No, there is no "standard" way of dealing with this. Certainly, you can use an if statement. However, a foreach (if you're planning to iterate over the contents) works just fine so long as the list is empty (but not if it's null).

A better approach would be to use an Editor/DisplayTemplate to render the collection, which will automatically deal with the collection if it's null or empty.

Yet another way would be to use a foreach with a null coalescing operator if the collection could be null to create an empty list in that case.

You have to think about the various options in order to decide which one works best for your situation.

Upvotes: 0

Travis J
Travis J

Reputation: 82287

There is nothing wrong with using a razor if statement to control DOM as it is being rendered. Although, you might want to make sure your list is instantiated or you will get an exception "Object reference not set to an instance of an object."

@if( Model.someList != null && Model.someList.Count > 0 )
{
 <div>@someList.Count</div>
}

Upvotes: 1

Related Questions