Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to call Action Method in ASP.NET MVC C# by Ajax

I have tried for hours to get this working, and I am really hoping one of you knows (a heck of a lot) more about this than I. When the client keys up in a textbox, I would like to call the MVC C# controller method called updateOrder(). Ideally, I would like to access form elements with a FormCollection (the form is called "createOrder").

In the controller, I have:

C#

[WebMethod]
public static void updateOrder(){
    string s = "asdf";
}

The string declaration above is breakpointed. In the view, I have a method I basically copy and pasted that I found on stackoverflow:

JavaScript

function updateOrderJS() {
    var $form = $('form[id="createOrder"]');
    $.ajax({type    : "POST",
        url     : $form.attr('action'),
        data    : $form.serialize(),
        error   : function(xhr, status, error) {},
        success : function(response) {
             updateOrder();
        }
    });
    return false;
}

The event is simply:

JavaScript

updateOrderJS();

The updateOrderJS() method fires (checked with an alert), but the breakpoint does not.

like image 501
user4855057 Avatar asked May 08 '15 21:05

user4855057


People also ask

How can call action method in jQuery in MVC?

Below is an example of calling a controller action called "GetData" using javascript/jquery. var url = '@Url. Action("GetData")'; $. ajax({ url: url, type: 'GET', cache: false, data: { value: strId}, success: function (result) { $('#result').


1 Answers

In Asp.Net MVC, you do not need to decorate your method with WebMethod. You just create an Action (which is a method) and return a result from it. For sample:

public class CustomerController : Controller 
{
   public ActionResult Index() 
   {
       return View();
   }

   [HttpPost]
   public ActionResult UpdateOrder()
   {
      // some code
      return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
   }
}

And in your View, you could try a javascript like this (using the $.ajax jquery method -- see the comments):

$.ajax({
    url: '@Url.Action("UpdateOrder")', // to get the right path to controller from TableRoutes of Asp.Net MVC
    dataType: "json", //to work with json format
    type: "POST", //to do a post request 
    contentType: 'application/json; charset=utf-8', //define a contentType of your request
    cache: false, //avoid caching results
    data: {}, // here you can pass arguments to your request if you need
    success: function (data) {
         // data is your result from controller
        if (data.success) { 
            alert(data.message);
        }
    },
    error: function (xhr) {
        alert('error');
    }
});
like image 135
Felipe Oriani Avatar answered Sep 30 '22 13:09

Felipe Oriani