11

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.

2
  • Can you debug and see the value you are getting in $form.attr('action')? Commented May 8, 2015 at 21:30
  • change "type" to "method" in your ajax call e.g. method : "POST" instead of: "type : "POST" Commented May 8, 2015 at 21:41

4 Answers 4

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');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Felipe, your awesome. I'm sure other answers may have been correct, and I chose yours because it was pretty much plug and play (so-to-write). Now I can start adding the server-side code. Thank you
3

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.

Comments

0
  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.

2 Comments

I'm not the one who downvoted you. But I don't think MVC Urls generally include page.aspx. The datatype and contentType might affect whether the model binder works, but I'm not sure it'd affect whether the route gets called at all. And the asker already said in his question that he verified that updateOrderJS() was getting called.
The WebMethodAttribute is used in web forms, as are static methods, therefore I thing there is confusion here. I added a note at the bottom to explain this too.
0

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.

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.