Razor C# Variables
Variables in Razor are used to store and manipulate data within your server-side logic. Razor supports C# variable declarations and operations seamlessly within your HTML and code blocks.
Key Topics
Declaring Variables
Example
@{
string name = "John";
int age = 30;
}
<p>Name: @name</p>
<p>Age: @age</p>
Explanation: This example demonstrates how to declare variables of different types and use them to render content dynamically in HTML.
Using Variables in HTML
Example
@{
string message = "Welcome to Razor!";
}
<h1>@message</h1>
Explanation: Razor variables can be used directly in HTML by prefixing them with the @
symbol, allowing seamless integration of dynamic data into your markup.
Performing Operations with Variables
Example
@{
int x = 5;
int y = 10;
int sum = x + y;
}
<p>The sum of @x and @y is @sum.</p>
Explanation: Razor allows you to perform mathematical operations with variables and display the results dynamically in your HTML.
Key Takeaways
- Variables in Razor follow standard C# syntax and support multiple data types.
- They can be seamlessly embedded into HTML for dynamic content rendering.
- Perform operations with variables to compute and display dynamic results.