开发者

Invoke controller from a javascript function

开发者 https://www.devze.com 2023-02-26 06:35 出处:网络
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 bas

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 contro开发者_Go百科ller's method looks like:

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

   object = //do the query.

   return View(object);


 }


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

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消