bb2
bb2

Reputation: 3

Invoke controller from a javascript function

I'm trying to call a controller method from a javascript function, I read that it can be used with jquery .ajax. The thing is that I don't want to receive a result, the controller renders a view based on the id that I send via the ajax. I have the following code, but it doesn't do anything...

(This function is called by a flash object)

function display(number) {

       $.ajax({
          type: "POST",
          url: "/Controller/Method",
          data: "id=" + number});

}

Here's what the controller's method looks like:

 [HttpPost]
 public ActionResult Method(int? id) {

   object = //do the query.

   return View(object);


 }

Upvotes: 0

Views: 253

Answers (3)

Russ Cam
Russ Cam

Reputation: 125538

You can return a PartialView which will return HTML that you can use to update the DOM but it sounds like you just want to make a request to a url directly, in which case, simply do

window.location = "/url_to_you_controller_action/{id to view}";

Assuming that you have a route that matches the url that you are making a request to, the controller action can take the id from the route values.

AJAX requests are generally for when you want to communicate with the server without performing a full page request and refresh. Usually that communication returns something, but not always, but if it does return something then it is common to manipulate the DOM in some way with the data returned from the server.

Upvotes: 0

Marek Karbarz
Marek Karbarz

Reputation: 29324

You could return a JsonResult if you detect an AJAX request:

if (Request.IsAjaxRequest()) {
    return Json(new { Status = "OK" });
} else {
    return View();
}

Upvotes: 1

neeebzz
neeebzz

Reputation: 11538

If you want to update your HTML through ajax, you should update the contents of your website in the callback function of your ajax request. If you simply want to navigate to a new page with the HTML returned just then use the window.location method.

Both cases, ensure you do it on the success callback function of your ajax call.

Upvotes: 1

Related Questions