What is the difference between @Url.Content("~/css/bootstrap.css") and only "/css/bootstrap.css"

Asked

Viewed 353 times

4

I am learning to program an application based on MVC4 and Bootstrap. At the beginning of the project I came across a puzzle:

In the _Layout.cshtml I had <link href="css/bootstrap.css" rel="stylesheet">, Bootstrap worked well on one view (Home/BootSchool) and the other did not format HTML (Student/AllStudents). After some research I solved my problem using <link href="@Url.Content("~/css/bootstrap.css")" rel="stylesheet">.

Does it have anything to do with the redirect? In the page source code, the link is the same in both modes and when I click on it I am redirected correctly to the Bootstrap CSS.

2 answers

5


This:

<link href="css/bootstrap.css" rel="stylesheet">

It’s not like this, as much as it seems:

<link href="@Url.Content("~/css/bootstrap.css")" rel="stylesheet">

In the first mode, the file path will be relative. That is:

/Student/AllStudents/css/bootstrap.css

In the second mode, you are clearly saying that the CSS source should be searched starting from the root, because you asked for the UrlHelper solve this for you (using the tilde, which indicates the root path of the route). That is to say:

/css/bootstrap.css

It is considered bad practice to reference a file without going through UrlHelper precisely because this relative route problem may occur.

  • 1

    I thought that would be exactly the difference, but I was surprised when I was redirected correctly in both cases to the correct file. The source code had exactly the same link for both cases(/css/bootstrap.css).

  • It is quite normal to put the reference fixed, but it is not a good practice because it makes room for problems.

3

They changed that in version 4. You can also use direct ~/css/file.css.

  • Just to leave a fountain New in ASP.NET MVC4: Razor changes. It means that <link href="~/css/bootstrap.css" rel="stylesheet"> should work on the correct MVC4?

  • I always use direct ~/css/bootstrap.css and never had a problem. Thanks for referencing an article. It was yesterday mobile is kind of complicated. Abs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.