Skip to content

4.6 View

1. C# in Views

You can write C# code directly in a view in ASP.NET MVC using Razor syntax, but it’s generally limited to lightweight logic for presentation purposes. Here are some common examples:

1.1 Declaring Variables

You can declare C# variables inside the view:

@{
var message = "Hello, World!";
int number = 10;
}
<p>@message</p>
<p>The number is: @number</p>

This will output:

Hello, World!
The number is: 10

1.2 Conditional Statements

You can use if-else or switch statements in the view:

@{
bool isLoggedIn = true;
}
@if (isLoggedIn)
{
<p>Welcome back, user!</p>
}
else
{
<p>Please log in.</p>
}

1.3 Loops

You can use for, foreach, or while loops to iterate over data.

@{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
}
<ul>
@foreach (var number in numbers)
{
<li>@number</li>
}
</ul>

This will display the numbers in an unordered list.

1.4 Functions

Although you should keep logic in the controller or model, you can define lightweight helper methods in the view.

@functions {
public string Greet(string name)
{
return $"Hello, {name}!";
}
}
<p>@Greet("John")</p>

This will output:

Hello, John!

1.5 Using LINQ

You can use LINQ expressions to manipulate data collections.

@{
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();
}
<p>Even numbers:</p>
<ul>
@foreach (var num in evenNumbers)
{
<li>@num</li>
}
</ul>

1.6 Rendering Partial Views Conditionally

You can use conditional logic to render partial views or components.

@if (Model.IsAdmin)
{
@Html.Partial("_AdminPanel")
}
else
{
<p>You do not have access to the admin panel.</p>
}