Possible breaking change in MVC4 Razor that can be fixed with “@:@”

只愿长相守 提交于 2019-11-26 21:49:00

问题


I recently upgraded my website from ASP.NET MVC3 (Razor) to MVC4 (Razor2), and in doing so found what seemed like a breaking change in the Razor view engine.

The scenario (greatly simplified) is shown below.

@model IEnumerable<string>

@{ Layout = null; }

<!DOCTYPE html>

<html>
    <body>
        <div>
              @foreach (var x in Model)
              {
                  @string.Format("Foo bar: {0}", x) // Errors in MVC4/Razor2
              }
        </div>
    </body>
</html>

This works fine in MVC3/Razor, however in MVC4/Razor2 the string.Format line results in an error of:

Unexpected "string" keyword after "@" character. Once inside code, you do not need to prefix constructs like "string" with "@".

If you remove the @, the view engine then demands that you terminate the string.Format line with a semicolon. However, ReSharper then warns (rightly so):

Return value of pure method is not used.

The two fixes I've found for this are either to use <text>:

<text>@string.Format("The value {0}", x)</text>

Or a more curious approach using @:@:

@:@string.Format("The value {0}", x)

Is this a known and documented change in the Razor view engine?


回答1:


Seems like a bug. It works with String:

@foreach (var x in Model)
{
    @String.Format("Foo bar: {0}", x)
}



回答2:


This is indeed a bug we decided not to fix, note that the syntax is incorrect as there is no transition between C# and markup in this case.

I understand that resharper shows a warning here but I believe the warning is wrong.

Here is the bug for future reference https://aspnetwebstack.codeplex.com/workitem/458



来源:https://stackoverflow.com/questions/15543841/possible-breaking-change-in-mvc4-razor-that-can-be-fixed-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!