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

后端 未结 4 429
夕颜
夕颜 2020-12-16 18:09

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 l

4条回答
  •  北海茫月
    2020-12-16 19:01

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

提交回复
热议问题