- 1 year ago
How do I add dynamic HTML to ASP.NET Razor
In ASP.NET Razor, you can add dynamic HTML by embedding C# code within HTML tags using the @
symbol. Here's an example:
html<div>
@for (int i = 0; i < Model.Count; i++)
{
<p>@Model[i].Name</p>
}
</div>
In this example, we are using a for
loop to iterate over a collection of data items in the Model
object, and adding a <p>
element for each item. The @
symbol is used to indicate that we are embedding C# code within the HTML tag.
You can also use conditional statements, expressions, and other C# constructs to generate dynamic HTML. For example:
html<div>
@if (Model.Count == 0)
{
<p>No data to display</p>
}
else
{
<ul>
@foreach (var item in Model)
{
<li>@item.Name</li>
}
</ul>
}
</div>
In this example, we are using an if
statement to check if the Model
object contains any data items, and displaying a message if it does not. If there are data items, we are using a foreach
loop to iterate over them and generate an <li>
element for each item.
Note that it's important to properly encode any user input or data that you include in dynamic HTML to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. You can use the Html.Encode
method or other encoding methods to ensure that any user input is properly encoded.