4

We are in the process of upgrading a .NET mvc app from MVC3 to MVC5, which includes an upgrade from Razor 1 to Razor 3. One error we keep hitting in views is the following:

In MVC3, many of our views do this:

@if (someCondition)
{
    @* render some content *@
    @string.Format(...)
}

However, in MVC5 this gives the following error:

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

There are two easy fixes that I know of:

@if (someCondition)
{
    @* render some content *@
    @: @string.Format(...)
}

Or

@if (someCondition)
{
    @* render some content *@
    <text> @string.Format(...) </text>
}

However, it will be painful to make and test these changes across hundreds of views. Thus my question is: what is the best way to address this seemingly breaking change?

  • Is there some kind of flag we can turn on to make razor behave as it used to?
  • What is the recommended style for this kind of construct in Razor 3?
ChaseMedallion
  • 20,860
  • 17
  • 88
  • 152
  • possible duplicate of [Possible breaking change in MVC4 Razor that can be fixed with "@:@"](http://stackoverflow.com/questions/15543841/possible-breaking-change-in-mvc4-razor-that-can-be-fixed-with) – Richard Ev Sep 11 '14 at 12:17

2 Answers2

2

I think the answer to this question may provide some help. While I don't know of, and there may not be, a particular flag you can turn on in the settings, if you just replace @string with @String (thus using the class and not the alias), it seems to work just fine.

@if (condition)
{
    @String.Format("test {0}", 2992)
}

Hopefully that would be as simple as just find/replacing any instance of "@string" with "@String" in your code.

Community
  • 1
  • 1
ryanulit
  • 4,983
  • 6
  • 42
  • 66
2

Hi you can use like this,

@if (someCondition)
{
    string.Format(...)
}

No need for do this,

@if (someCondition)
{
    @* render some content *@
    @: @string.Format(...)
}

Or

@if (someCondition)
{
    @* render some content *@
    <text> @string.Format(...) </text>
}
Jaimin
  • 7,964
  • 2
  • 25
  • 32
  • 1
    This will not work in Razor 3. You will get a "; expected" error if you try string.format() and do not include the semicolon. Also, if you do include the semicolon, it still will not display because you haven't output the return value of the function to the view. – ryanulit Apr 09 '14 at 13:04