Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing text and functions inside an if/else with MVC Razor

Tags:

I have the following code inside a partial view:

@if (Request.IsAuthenticated) {     Hello, @Html.ActionLink(User.Identity.Name, "ChangePassword", "Account") | Html.ActionLink("Log off", "LogOff", "Account") } else {     @Html.ActionLink("Log in", "Login", "Account") } 

Expected output (with appropriate links to actions):

  • If logged in: Hello Jim | Log off
  • If not logged in: Log in

However, this results in errors:

  • Within VS, The word "Hello" has an error on it: "Cannot resolve symbol 'Hello'" and "&#" has "Expression expected"
  • In the browser I get "CS1040: Preprocessor directives must appear as the first non-whitespace character on a line"

If I put a <p>...</p> around the line beginning with "Hello" the error goes away.

There is obviously some syntax error with my mixing calls to @Html and text within the same line. What is the correct way to do this?

like image 344
Yaakov Ellis Avatar asked Apr 18 '12 13:04

Yaakov Ellis


People also ask

Can you mix Razor pages and MVC?

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.

Does 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.

Is Razor better than MVC?

From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.


1 Answers

The contents of a code block ({ ... }) are expected to be code, not markup.

If you want to put text directly in a code block, you have three choices:

  • Wrap it in any HTML tag
  • Wrap it in the special Razor <text> tag, which will just render the text without the tag
  • Prepend the line with @:, which is equivalent

See SottGu's blog post.

like image 136
SLaks Avatar answered Sep 18 '22 09:09

SLaks