MVC 3 Razor Syntax for straight text output?

asp.net Mvc-3

asp.net Mvc-3 Problem Overview


Using Razor how/can you write straight text with out wrapping it in some type of html tag?

Example (This works but adds extra span tags):

@{ var foo = true; }
@if(foo) { <span>Yes</span> } else { <span>No</span> }

I'd like to keep my final markup as clean as possible and not have the extra tags.

Thanks!

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

use the <text> tags

@{ var foo = true; }
@if(foo) { <text>Yes</text> } else { <text>No</text> }

The <text> tag signals to the razor view engine to write the contents to the output.

Alternatively, you can use @:

@{ var foo = true; }
@if(foo) { @:Yes } else { @:No }

Solution 2 - asp.net Mvc-3

A point worth to be noted here:

@: can be used only inside an @

(in case any body like me is wondering why @: does not work!)

Solution 3 - asp.net Mvc-3

If you're trying like I am to inject data into Javascript I found this to work.

@Html.Raw(table)

I was pulling data from a database and injecting it into the code for a Google chart.

So in the OP's case,

@if (foo) { Html.Raw("Yes") } else { Html.Raw("No") }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmatto0View Question on Stackoverflow
Solution 1 - asp.net Mvc-3Russ CamView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3BountyView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3KSummersView Answer on Stackoverflow