I am having issues with displaying (rather NOT displaying) plain text in an else block.
if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>
<table>
<tr>
<th></th>
<th>Careerfield Name</th>
</tr>
@foreach (var item in Model.CareerFields)
{
<tr>
<td>
@Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
</td>
<td>
@item.CareerFieldName
</td>
</tr>
}
</table>
}
else
{
No Careerfields associated with @ViewBag.SelectedDivisionTitle
}
The if blocks works fine. The text only renders when true. However, the else block text renders when the page loads, not if it evaluates to false only.
I've tried using
Hmtl.Raw("No Careerfields associated with ")
<text>No Careerfields associated with @ViewBag.SelectedDivisionTitle</text>
@:No Careerfields associated with @ViewBag.SelectedDivisionTitle
But it still renders the plaintext before evaluation.
Any suggestions?
The If Condition The if statement returns true or false, based on your test: The if statement starts a code block. The condition is written inside parenthesis. The code inside the braces is executed if the test is true.
In Razor, `@` symbol is used to transition from HTML to C#. To escape an '@' symbol in razor markup, use two '@' symbols.
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. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
Put your "plain text" inside of a naked <span>
tag:
else
{
<span>No Careerfields associated with @ViewBag.SelectedDivisionTitle</span>
}
The browser shouldn't render it special (unless you have css selecting every span) and it'll help razor sense the end of the C# and print your HTML.
The following code worked perfectly for me:
@if (false) {
<h3>
Careerfields Listing
</h3>
<table>
<tr>
<th>
</th>
<th>
Careerfield Name
</th>
</tr>
</table>
}
else
{
@:No Careerfields associated with @ViewBag.SelectedDivisionTitle
}
You can see that the contents of if are rendered when you change condition to true.
Looks like you've forgotten the @
sign before your if
statement. Try this:
@if (Model.CareerFields != null && ViewBag.CFCount > 0)
{
<h3>Careerfields Listing</h3>
<table>
<tr>
<th></th>
<th>Careerfield Name</th>
</tr>
@foreach (var item in Model.CareerFields)
{
<tr>
<td>
@Html.ActionLink("Select", "Index", new { careerFieldID = item.CareerFieldId })
</td>
<td>@item.CareerFieldName</td>
</tr>
}
</table>
}
else
{
<text>No Careerfields associated with @ViewBag.SelectedDivisionTitle</text>
}
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