views:

44

answers:

2

If I have a Controller called "HomeController" and I'm on the Index page of that controller, how can I do a jQuery Ajax post to another controller.

I tried the below,

    $.post("/DetailedQuote/jQueryGetDetailedQuote", { productCode: "LPJ" }, function(newHTML) {
        alert(88);
    });

I have a DetailedQuoteController.

I have also tried;

post("DetailedQuote/
post("DetailedQuote.aspx/
post("/DetailedQuote.aspx/
post("/DetailedQuoteController/
post("DetailedQuoteController/
post("DetailedQuoteController.aspx/
post("/DetailedQuoteController.aspx/

And still no joy.

I should also mention that this is running a Hybrid WebForms and MVC site on IIS 6.

EDIT

The error that is being returned in error: is "error" so I assume that's maybe a 404.

In fact, it is a 404. I just checked.

A: 

There doesn't appear to be anything wrong with your jQuery command, so the most obvious place to start looking is in the controller itself. Things to check would be:

  • Does your Controller action return a Json response (e.g. public JsonResult jQueryGetDetailedQuote)?
  • Are you using the Json() method to return your object?
  • Do you have your action decorated with the [HttpPost] attribute?

Perhaps you could post part of your controller code as well?

I notice that in your jQuery method you're calling an action called jQueryGetDetailedQuote. If your intention is purely to just GET a result, then perhaps you should use jQuery's $.get() or $.getJSON() functions instead?

Phil.Wheeler
@Phil, thanks for the reply. At present the controller code is empty other than the method stub. I can happily post to a method in the same controller that the page is being served from but not to another. I suspect it might have something to do with IIS 6
griegs
+1  A: 

This should work:

public class DetailedQuoteController : Controller
{
    [HttpPost]
    public ActionResult GetDetailedQuote(string productCode)
    {
        return Json(new { Code = productCode, Quote = 123 });
    }
}

And to invoke it first declare a global javascript variable containing the address of this controller somewhere inside the view:

var quoteAddress = '<%= Url.RouteUrl(new { controller = "DetailedQuote", action = "GetDetailedQuote" }) %>';

And finally call the method:

$(function() {
    $.post(quoteAddress, { productCode: 'LPJ' }, function(json) {
        alert(json.Quote);
    });
});
Darin Dimitrov