Calling a MVC2 partial view using jquery returns empty string
I have an issue where I have a partial view that returns some HTML to be displayed. Its called when something is clicked on the page using jquery. The problem is that no matter how I call it, i get back an empty string even though it reports success. This is happening to me using Chrome, going against my local machine.
My controller looks like this:
public ActionResult MyPartialView()
{
return PartialView(model);
}
I have tried jquery using .get(), .post() and .load() and all have the same results. Here is an example using .post():
$.post(url, function (data)
{
alert(data);
});
The result always comes back as an empty string. I can navigate to the partial view in the browser manually and i get back the desired HTML. The URL I am using to call it I resolved fully so it looks like "http://localhost/controller/mypartialview" rather than using the relative path of "/controller/mypartia开发者_JAVA百科lview" which I thought was the original problem. Any idea what may cause this?
It's hard to tell what the problem is. If you have a correct view of your html when accessing the same URL via the browser, that means your server side is good to go (w/ HTTP GET).
So then I would say that the problem is in the jQuery usage. Try hard coding the url into the jQuery code, so that you make sure jQuery is getting the right url.
$.get( 'http://localhost/controller/mypartialview', function(data){ alert(data); } );
Did you set the
$.ajax
global options? (Not that you need to, just maybe you set something up previously, and that's messing up your new request)Make sure you aren't sending any query when accesed thru Browser. Which might make it work via Browser and not through jQuery.
I definitely recommend you to install Firefox and Firebug, to do a better debug of your AJAX requests.
I figured it out. At first I thought I had to resolve the URL completely starting with the http:// but I accidentally forgot to include the port that the visual studio webserver was using. It just used http://localhost/ instead of http://localhost:2858/ as the base. Once I changed it back to use the relative path instead, it started working. I am guessing jquery resolves relative paths for you based on the current page's url in the ajax methods.
精彩评论