scottm scottm - 2 months ago 9
jQuery Question

jQuery posts data to wrong relative URL

I have an ASP.Net MVC application. I am trying to post data to an action, and then just render the output. I have a page where you can view a product, so www.mysite.com/product/details/1 shows the product. On this page, I render a partial view through RenderAction() that contains some pricing logic. I want the user to select some options and then have jquery post the options to get the new price.

However, when I call

$.post({
url : "price/getprice",
data : {"options" : chosenOptions},
success : function(data) {
$("#price").text(data);
}
});


The url is posting to
www.mysite.com/product/details/price/getprice
which doesn't exist. I've tried posting to "~/price/getprice/" but it does the same thing. Why won't it go to my PriceController's GetPrice(FormCollection form) action??

This should post to
www.mysite.com/price/getprice
. When I look in the Net tab in firebug, it says it's posting this:

http://localhost:42427/Product/Details/%5Bobject%20Object%5D


If I look at the response in Firebug, the application is throwing an exception:


The parameters dictionary contains a
null entry for parameter 'id' of
non-nullable type 'System.Int32' for
method 'System.Web.Mvc.ActionResult
Details(Int32)' in
'PrintPlaceWebsite.Controllers.ProductController'.


But I'm not trying to post to that location so...ugh.

Answer

Well you specified a relative URL, so if this code is on site www.mysite.com/a/b/c, the URL will point to /a/b/price/getprice.

You probably want to specify an absolute URL:

$.post({
  url : "/price/getprice",
  //     ^-- leading slash
  data : {"options" : chosenOptions},
  success : function(data) {
              $("#price").text(data);
            }
});
Comments