How to display conditional plain text with a razor

I'm having trouble displaying (rather than 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 } 

If blocks work fine. Text is only displayed when true. However, the text of the else block displays when the page loads, and not only if it only evaluates to false.

I tried using

 Hmtl.Raw("No Careerfields associated with ") <text>No Careerfields associated with @ViewBag.SelectedDivisionTitle</text> @:No Careerfields associated with @ViewBag.SelectedDivisionTitle 

But before evaluating it still provides clear text.

Any suggestions?

+8
asp.net-mvc-3 razor
source share
3 answers

Put your "plain text" inside the open <span> :

 else { <span>No Careerfields associated with @ViewBag.SelectedDivisionTitle</span> } 

The browser should not make it special (unless you have a css that selects each interval), and this will help the razor to feel the end of C # and print your HTML.

+8
source share

The following code worked fine 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 displayed when the condition changes to true .

+4
source share

It looks like you forgot the @ sign before the if . Try the following:

 @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> } 
+2
source share

All Articles