Todd Davis
Todd Davis

Reputation: 6035

jQuery load() and ASP.NET MVC URL path

I am creating an MVC web app, and I want to load some page content in via AJAX using jQuery.load(). I have this working, but the problem is that I have to pass the ENTIRE URL in, including the http:// part, or it won't work. In other words, a relative URL path is failing.

So, this works:

$('#params').empty().load('http://localhost:58438/home/getsurveydata #params', val);

This fails:

$('#params').empty().load('/home/getsurveydata #params', val);

Every example I see on the web seems to indicate that the second form should work just fine. Any thoughts?

FWIW I tried removing the 'val' part and the #params part, but that made no difference. It doesn't even hit the controller. And like I said, it works in the first format with as written, the URL is the only difference. What am I missing?

Upvotes: 0

Views: 1042

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

How about using HTML5 data-* attributes on the #params container:

<div id="params" data-url="@Url.Action("getsurveydata", "home")"></div>

Now in your separate javascript you can write:

var p = $('#params');
p.empty().load(p.data('url') + ' #params', val);

This will work no matter where the application is deployed and it avoids you from hardcoding any urls as it relies on url helper to generate it so if you decide to change the layout of your routes in Application_Start you won't need to modify anything on the UI part.

Upvotes: 3

endyourif
endyourif

Reputation: 2202

Doesn't make sense to me why it doesn't work, but worse-case scenario you can make it dynamic by using this:

$('#params').empty().load('http://@HttpContext.Current.Request.Url.Authority/home/getsurveydata #params', val);

Upvotes: 0

Related Questions