0

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);


 }

3 Answers 3

1

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

if (Request.IsAjaxRequest()) {
    return Json(new { Status = "OK" });
} else {
    return View();
}
Sign up to request clarification or add additional context in comments.

4 Comments

I don't want to return an object, I wanted to know if that is possible. I only want to return a view...
So you want to get the View using AJAX and display it? Sorry, I guess I misunderstood your question.
The ajax posts the id of an object to be found by the controller method and the controller method returns a view with the object that it searched for in the database.
Yes, i think i will return a JSON object, it doesn't make sense, it will be better, i thought about it. Thanks!! Plus I am calling the same view. The view with the ajax calls the controller method and the controller method returns the same view but with additional info based on what was sent by the ajax.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.