Search code examples
c#razorasp.net-mvc-5asp.net-mvc-views

Error when declaring and using a string


How can I reference a variable that I have created in a MVC Razor View?

I have declared a variable as follows:

@string bootstrapCSSPath = @Path.Combine(Model.pathToResourceDirectory, "bootstrap/css/bootstrap.min.css");

Now I wish to use this variable in html.

Here is my code:

<link href="@bootstrapCSSPath" rel="stylesheet" type="text/css" />

When the View is displayed, the following error is shown:

Compiler Error Message: CS1525: Invalid expression term 'string'


Solution

  • In Razor you can declare variables or use c# code by using parantheeses {}, in your case:

    @{
       string bootstrapCSSPath = @Path.Combine(Model.pathToResourceDirectory, "bootstrap/css/bootstrap.min.css");
    }
    

    and

    <link href=@Html.Raw(bootstrapCSSPath) rel="stylesheet" type="text/css" />
    

    you can lool on this blog for more information