How to run Url.Content via Client?

2

In ASP.NET MVC, you can run @Url.Content on views and controllers. This variable returns the relative level the site is in.

My question is: how to run Url.Content via JavaScript? Is there any way in MVC?

EDITED

Example of @Url.Content in C #

<img src="@Url.Content("~/Content/img/teste.jpg")" />

Ambient result

| DEV | /Content/img/teste.jpg" |
| PRD | /NovoSite/Content/img/teste.jpg" |

In my case, the production environment is inside a "NovoSite" folder, using @Url.Content I do not need to worry about this. But if I do something with javascript / jquery example

$("#element").html('<img src="/Content/img/teste.jpg" />');

It will only work in my Dev environment, and I need to change the path every time I do a deploy

    
asked by anonymous 07.02.2014 / 02:33

3 answers

1

Use instead of ~ a . to indicate that it is relative to the position of HTML.

$("#element").html('<img src="./Content/img/teste.jpg" />');

If your page is in /NovoSite/ it will be: NovoSite/Content/img/teste.jpg

Or just do not put / at the beginning, it will also work as a relative address.

    
07.02.2014 / 12:52
1

Use the pseudo text element so that the Razor engine can consider C # expressions within JavaScript code. In your case, try the following:

<text>
    $("#element").html('<img src="@Url.Content("~/Content/img/teste.jpg")" />');
</text>
    
07.02.2014 / 12:52
0

James, you already have some good solutions there. I will add an alternative that is how I work. It is often useful to save the root address of your site to some variable. I inject this into HTML, like this:

<input type="hidden" id="_urlRoot" value="@Url.Content("~/")" />

If you prefer direct in JS:

var urlRoot = '@Url.Content("~/")';

To access, I leave a function similar to this in a common JS file:

    function setURL(path) {
        return $('#_urlRoot').val() + path;
    }

And the use:

$("#element").html('<img src="' + setU('Content/img/teste.jpg') + '" />');
    
07.02.2014 / 21:49