Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple increment of a local variable in views in ASP.NET MVC3 (Razor)

Tags:

razor

Well, this is just embarrassing. I can't even figure out a simple increment in one of my views in ASP.NET MVC3 (Razor). I have done searches and it appears that the documentation for Razor is pretty sparse. Here is what I have tried and failed miserably:

@{     var counter = 1;      foreach (var item in Model.Stuff) {         ... some code ...         @{counter = counter + 1;}     } }    

I have also tried @{counter++;} just for kicks and to no avail =) I would appreciate it if someone could enlighten me. Thanks!

like image 974
Allen Liu Avatar asked Sep 23 '11 21:09

Allen Liu


People also ask

How do you assign a value to a variable in Razor view?

To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.

What is @model in Razor?

The @ symbol is used in Razor initiate code, and tell the compiler where to start interpreting code, instead of just return the contents of the file as text. Using a single character for this separation, results in cleaner, compact code which is easier to read.

What is Razor in MVC What are the main Razor syntax rules?

Razor is a simple programming syntax for embedding server code in web pages. Razor syntax is based on the ASP.NET framework, the part of the Microsoft.NET Framework that's specifically designed for creating web applications.

What is Razor view in C#?

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.


2 Answers

@{     int counter = 1;      foreach (var item in Model.Stuff) {         ... some code ...         counter = counter + 1;     } }   

Explanation:

@{ // csharp code block // everything in here is code, don't have to use @ int counter = 1; }  @foreach(var item in collection){     <div> - **EDIT** - html tag is necessary for razor to stop parsing c#     razor automaticaly recognize this as html <br/>     this is rendered for each element in collection <br/>     value of property: @item.Property <br/>     value of counter: @counter++     </div> } this is outside foreach 
like image 144
Goran Obradovic Avatar answered Sep 18 '22 11:09

Goran Obradovic


I didn't find the answer here was very useful in c# - so here's a working example for anyone coming to this page looking for the c# example:

@{ int counter = 0; }   @foreach(Object obj in OtherObject) {     // do stuff     <p>hello world</p>     counter++; } 

Simply, as we are already in the @foreach, we don't need to put the increment inside any @{ } values.

like image 40
johnwinter Avatar answered Sep 18 '22 11:09

johnwinter