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!
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.
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.
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.
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.
@{ 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
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.
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