Reputation: 1347
I have a relative path:
~/Content/themes/base/jquery-ui.min.css"
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")"/>
and
<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 UriBuilder
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 /Content/themes/base/jquery-ui.min.css
and in my MVC controller I tried:
Page.ResolveClientUrl("~/Content/themes/base/jquery-ui.min.css");
which also doesn't do what I need.
Background:
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:
http://localhost/~/Content/themes/base/jquery-ui.css
If I just remove the ~/
then it works http://localhost/Content/themes/base/jquery-ui.css
, but when I click to go to a new link the path is no longer good: http://localhost/newLink/Content/themes/base/jquery-ui.css
The Url on my localhost is http://localhost/Content/themes/base/jquery-ui.css
and on my server its http://server/productName/Content/themes/base/jquery-ui.css
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?
Upvotes: 0
Views: 1433
Reputation: 239460
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();
}
}
Upvotes: 2