I have problem with IF statement inside MVC View. I am trying to use it for creating row for every three items.
<div class="content"> <div class="container"> @if (ViewBag.Articles != null) { int nmb = 0; foreach (var item in ViewBag.Articles) { if (nmb % 3 == 0) { <div class="row"> } <a href="@Url.Action("Article", "Programming", new { id = item.id })"> <div class="tasks"> <div class="col-md-4"> <div class="task important"> <h4>@item.Title</h4> <div class="tmeta"> <i class="icon-calendar"></i> @item.DateAdded - Pregleda:@item.Click <i class="icon-pushpin"></i> Authorrr </div> </div> </div> </div> </a> if (nmb % 3 == 0) { </div> } } } </div> </div>
The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.
Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
A file with . cshtml extension is a C# HTML file that is used at server side by Razor Markup engine to render the webpage files to user's browser. This server side coding is similar to the standard ASP.NET page enabling dynamic web content creation on the fly as the webpage is written to the browser.
You only need to prefix an if
statement with @
if you're not already inside a razor code block.
Edit: You have a couple of things wrong with your code right now.
You're declaring nmb
, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:
@if (ViewBag.Articles != null) { int nmb = 0; foreach (var item in ViewBag.Articles) { if (nmb % 3 == 0) { @:<div class="row"> } <a href="@Url.Action("Article", "Programming", new { id = item.id })"> <div class="tasks"> <div class="col-md-4"> <div class="task important"> <h4>@item.Title</h4> <div class="tmeta"> <i class="icon-calendar"></i> @item.DateAdded - Pregleda:@item.Click <i class="icon-pushpin"></i> Authorrr </div> </div> </div> </div> </a> if (nmb % 3 == 0) { @:</div> } } }
The important part here is the @:
. It's a short-hand of <text></text>
, which is used to force the razor engine to render text.
One other thing, the HTML standard specifies that a
tags can only contain inline elements, and right now, you're putting a div
, which is a block-level element, inside an a
.
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With