Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Possible breaking change in MVC4 Razor that can be fixed with "@:@"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Seems like a bug. It works with String:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...