Url.Content() not working on complex URLs

14,066

In ASP.NET MVC 4+, you do not need to use Url.Content in attribute values. Use the ~/ syntax directly and let razor view engine 2 process the path for you. So your examples can be coded as follows:

<img src="~/Content/Images/logo.png" id="logo">

In the case you need to create a dynamic path, so, you have to use Url.Content, for sample:

@{
   string imagePath = Url.Content("~/Content/Images/stores/" + Model.PreferedCart.Store.Retailer.Id + ".png");
}
<img src="@imagePath"/>

If it does not work, the reason is because you have problems with your URL rewriter.

Share:
14,066
Antoine
Author by

Antoine

Lead developer at Swaven. Web enthusiast.

Updated on June 09, 2022

Comments

  • Antoine
    Antoine almost 2 years

    I have Url.Content() snippets everywhere in my views. They work fine on pages with a simple URL, but not when the URL gets longer.

    Here's a sample:

    <img src="@Url.Content("~/Content/Images/logo.png")" id="logo">
    

    This works fine when I'm on the homepage, or a page with URL localhost:8080/s/chocolate (which shows the result for the "chocolate" search.

    But when I'm trying to add some refinements, e.g. localhost:8080/s/chocolate/b/lindt (which means filter the previous results to only ones from brand Lindt), it doesn't work anymore. In this case, Url.Content points to /s/chocolate/Content/Images/logo.png, which obviously fails.

    It's as if Url.Content only goes 2 levels up the current location instead of using the real root of the web app. I guess it makes sense in the convention that URLs are in the form host/controller/action, but here I have a more complex URL scheme (I use URL rewriter module to match these URL fragments to action's parameters).

    Is there any way to tell the helper to go to the real root, or any other solution to this problem?

    (BTW, I'm using MVC 4)


    EDIT: As Felipe answered, I've just discovered that Url.Content is no longer necessary with MVC 4. That works for all "design" images with a constant path. However, I use a lot of images where the path is constructed partly with some data, e.g.

    <img src="@Url.Content(string.Format("~/Content/Images/stores/{0}.png", cart.Store.Retailer.Id))"/>
    

    I simply removed the Url.content, as such:

    <img src="@string.Format("~/Content/Images/stores/{0}.png", Model.PreferedCart.Store.Retailer.Id)"/>
    

    When rendered, this gives the following src: ~/Content/Images/stores_v2/Fr_SimplyMarket.png. The ~ being still here, the image is not found. How can I fix that?