Noctane Noctane - 11 months ago 55
Javascript Question

Get relative URL in MVC 4

I have a relative path:


and I have a hidden input:

<input type="hidden" id="siteUrl" value=""/>

In MVC I want to store the fully qualified URL into the hidden field. I have tried:

<input type="hidden" id="siteUrl" value="@Url.RequestContext.HttpContext.Request.MapPath("~/Content/themes/base/jquery-ui.min.css")"/>


<input type="hidden" id="siteUrl" value="@HttpContext.Current.Request.MapPath("~/Content/themes/base/jquery-ui.min.css")"/>

But those are both returning a physical path, I need the URL. I have also tried using
however this doesn't work for me because while it might work on my localhost it doesn't when I publish it to my IIS server.

I have also tried:

<input type="hidden" id="siteUrl" value="@Url.Content("~/Content/themes/base/jquery-ui.min.css")"/>

but it returns

and in my MVC controller I tried:


which also doesn't do what I need.


I store that FQ URL into the hidden field and then I access it in JS, in JS when I use a relative url it doesnt know how to use it correctly because with MVC for each link the path changes and it just tacks the relative string on to the end like this:

If I just remove the
then it works
, but when I click to go to a new link the path is no longer good:

The Url on my localhost is

and on my server its
I dont want to code for some static name in case the base server url were to change in the future.

So how do I get the fully qualified URL for a relative path?

Answer Source

I'm not sure what issues you were having with UriBuilder, but that's the best method:

    var uriBuilder = new UriBuilder(Request.Url);
    uriBuilder.Path = Url.Content("~/Content/themes/base/jquery-ui.min.css");
<input type="hidden" id="siteUrl" value="@uriBuilder.ToString()"/>

You start with Request.Url, so you don't have to hard code the host. That way, it should work everywhere you deploy it. Then you alter the Path, but you need to use Url.Content to replace the ~ with whatever it should be first.

You might want to actually add your own UrlHelper extension as well:

public static class UrlHelperExtensions
    public static string AbsoluteContent(this UrlHelper helper, string contentPath)
        return new Uri(helper.RequestContext.HttpContext.Request.Url, helper.Content(contentPath)).ToString();