2

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'

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Simon
  • 7,991
  • 21
  • 83
  • 163
  • `@{string bootstrapCSSPath = Path.Combine(Model.pathToResourceDirectory, "bootstrap/css/bootstrap.min.css");}` – Sachu May 27 '15 at 06:06

2 Answers2

1

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

israel altar
  • 1,768
  • 1
  • 16
  • 24
0

when declaring varibles in View it should enclosed in {}

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

see my comment in your question

Sachu
  • 7,555
  • 7
  • 55
  • 94