admin管理员组

文章数量:1181399

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.

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.

Share Improve this question edited May 8, 2015 at 22:16 Felipe Oriani 38.6k19 gold badges137 silver badges201 bronze badges asked May 8, 2015 at 21:27 user4855057user4855057 1951 gold badge3 silver badges11 bronze badges 2
  • Can you debug and see the value you are getting in $form.attr('action')? – JGV Commented May 8, 2015 at 21:30
  • change "type" to "method" in your ajax call e.g. method : "POST" instead of: "type : "POST" – Jorge Zuverza Commented May 8, 2015 at 21:41
Add a comment  | 

4 Answers 4

Reset to default 23

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

In MVC, you don't need the [WebMethod] stuff - you just can have a regular controller action returning an ActionMethod (or null if you don't need a return value). The WebMethod attribute with static methods is for WebForms, not MVC.

public ActionMethod updateOrder(MyModel someModel) {
    // Do something
    return null;
}

Your URL in the javascript would be the URL to that action, which you can get to in Razor using @Url.Action("updateOrder", "Orders"), where "Orders" is the name of your controller.

  1. Ensure "url" is in the format page.aspx/updateOrder.

  2. Specify datatype: json

  3. Ensure your updateOrderJS() is being called.

  4. Ensure contentType: "application/json; charset=utf-8" is included.

Note: [WebMethod] is used for calling webforms methods, not MVC.

It looks like you're putting the URL of the MVC route in the action attribute of your <form> tag. I can't see what that attribute looks like because you didn't post your html, but from what I can see the value of that attribute might be wrong.

Most of the time, the URL to a specific MVC action is http://ServerDomain/Path(IfAny)/ControllerName/ActionName. For example, if you have a controller and action like this...

public class StackController
{
    [HttpPost]
    public ActionResult Overflow()
    {
        return View();
    }
}

...and your ASP.NET application is deployed to www.example.com, the URL in the action attribute of your <form> tag would be http://www.example.com/Stack/Overflow.

Of course, it's possible for other settings in your ASP.NET MVC to change these URLs, such as the route setup in your global.asax's RegisterRoutes method, or perhaps if your controllers are divided into Areas. If the URL of your <form> looks correct, please post the html along with any relevant controller routing code in your ASP.NET app.

If your form is inside of a Razor view (cshtml file), you can use <form action="@Url.Action({ controller = "ControllerName", action = "ActionName" })" method="post"> to generate the correct form URL.

本文标签: javascriptjQuery to call Action Method in ASPNET MVC C by AjaxStack Overflow