Search code examples
c#.netasp.net-mvc-4razor-2

razor with MVC4.0 helper output with method call


@helper GetString()
{
    @string.Format("string_{0}","foo");               
}

Above code will not compile in ASP.NET MVC 4.0 with Razor 2.0. But if I remove '@' before string.Format, then the code compiles, but the string will not be outputed to the generated HTML. Why's this? In MVC 3.0 with Razor 1.x, above code works as expected. I walkaround this with below code by introducing a variable

@helper GetString()
{
    var url = string.Format("string_{0}","foo");               
    @url
}

Why is this?


Solution

  • @helper GetString()
    {
        @string.Format("string_{0}","foo");               
    }
    

    Above code will not compile in ASP.NET MVC 4.0 with Razor 2.0.

    That is because the razor engine will see that you have a construct (e.g. string in your example) and you are using the @ redundantly. That won't compile as you experienced it.

    But if I remove '@' before string.Format, then the code compiles, but the string will not be outputed to the generated HTML.

    Nothing will be outputted because you have not told the razor engine what to write. You just did some code. It is similar to doing in c# and doing a string.Format and not assigning it to a variable.

    I walkaround this with below code by introducing a variable

    In connection to what I've mentioned earlier, the minute you introduced a variable and wrote it, you are now telling the razor engine to output something. That is similar to a c# console app, wherein:

    • you did a string.Format: string.Format("string_{0}","foo");
    • assign its output to a variable: var url = string.Format("string_{0}","foo");
    • printed the variable: @url

    You can read this blog post to better understand how the razor engine works with regards to the usage of @.

    Now for an alternative to what you are doing, you can do this:

    @helper GetString()
    {        
        <text>@string.Format("string_{0}", "foo")</text>
    }