Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc razor - how to break out of C#

If I'm working on a view in Razor, and I'm currently in a code block and want to output something, how do I do this? To illustrate my question, I'm using echo from PHP below:

<p>
  @if (Model.NumberOfWidgets > 100)
  {
    echo(Model.NumberOfWidgets);
  }
  else
  {
    echo("There are loads of widgets.");
  }
</p>

So I'm using echo where I want to tell Razor that I'm not doing C# anymore, I'm meaning this should be written to the output. How do I do this?

Edit: I tried Response.Write, but that gets written before the view markup, at the top of the page!

like image 410
David Avatar asked Jan 18 '13 14:01

David


People also ask

How do you escape Razor syntax?

To escape an '@' symbol in razor markup, use two '@' symbols.

Can you debug Razor pages?

Set a breakpoint on line 17. Run the app again. You can even debug the Razor Pages with markup and inspect the values of variables!

Does ASP.NET MVC use Razor?

Razor is one of the view engines supported in ASP.NET MVC. Razor allows you to write a mix of HTML and server-side code using C# or Visual Basic. Razor view with visual basic syntax has .

Can you mix MVC and Razor pages?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.


2 Answers

<p>
  @if (Model.NumberOfWidgets > 100)
  {
    @Html.DisplayFor(m => m.NumberOfWidgets)
  }
  else
  {
    @:There are loads of widgets  //or <text>Thera are loads of widgets</text>
  }
</p>
like image 81
Raphaël Althaus Avatar answered Sep 25 '22 01:09

Raphaël Althaus


Begin your line with @: this will tell Razor that it's actually ouput that you want to show and not C# code.

<p>
  @if (Model.NumberOfWidgets > 100)
  {
    @: @Model.NumberOfWidgets
  }
  else
  {
    @: There are loads of widgets.
  }
</p>
like image 28
Yan Brunet Avatar answered Sep 26 '22 01:09

Yan Brunet