MVC 3 Razor Syntax for straight text output?

2020-05-29 12:46发布

问题:

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!

回答1:

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 }


回答2:

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!)