jQuery在Ajax中调用ASP.NET MVC C#中的Action Method

时间:2022-02-15 03:17: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").

我已经尝试了几个小时才能使这个工作,我真的希望你们中的一个人知道(很多)这个比我更多。当客户端在文本框中键入时,我想调用MVC C#控制器名为updateOrder()的方法。理想情况下,我想使用FormCollection访问表单元素(表单称为“createOrder”)。

In the controller, I have:

在控制器中,我有:

C#

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 *:

上面的字符串声明是breakpointed。在视图中,我有一个基本上复制和粘贴的方法,我在*上找到:

JavaScript

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

JavaScript的

updateOrderJS();

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

触发updateOrderJS()方法(使用警报检查),但断点不会触发。

4 个解决方案

#1


19  

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:

在Asp.Net MVC中,您不需要使用WebMethod来装饰您的方法。您只需创建一个Action(这是一个方法)并从中返回一个结果。样品:

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):

在你的视图中,你可以尝试这样的javascript(使用$ .ajax jquery方法 - 参见注释):

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

#2


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.

在MVC中,你不需要[WebMethod]东西 - 你可以有一个常规的控制器动作返回一个ActionMethod(如果你不需要返回值,则返回null)。具有静态方法的WebMethod属性适用于WebForms,而不适用于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.

您在javascript中的网址将是该操作的网址,您可以使用@ Url.Action(“updateOrder”,“Orders”)在Razor中获取该网址,其中“订单”是您的控制器的名称。

#3


0  

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

    确保“url”的格式为page.aspx / updateOrder。

  2. Specify datatype: json

    指定数据类型:json

  3. Ensure your updateOrderJS() is being called.

    确保正在调用updateOrderJS()。

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

    确保contentType:“application / json; charset = utf-8”包含在内。

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

注意:[WebMethod]用于调用webforms方法,而不是MVC。

#4


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.

看起来您将MVC路由的URL放在

标记的action属性中。我看不出那个属性是什么样的,因为你没有发布你的html,但从我看到的那个属性的值可能是错误的。

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

大多数情况下,特定MVC操作的URL是http:// ServerDomain / Path(IfAny)/ ControllerName / ActionName。例如,如果你有一个这样的控制器和动作......

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.

...并且您的ASP.NET应用程序已部署到www.example.com,

标记的action属性中的URL将为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.

当然,ASP.NET MVC中的其他设置可能会更改这些URL,例如global.asax的RegisterRoutes方法中的路由设置,或者如果您的控制器分为区域。如果您的

的URL看起来正确,请在您的ASP.NET应用程序中发布html以及任何相关的控制器路由代码。

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.

如果您的表单位于Razor视图(cshtml文件)中,您可以使用

来生成正确的表单URL。

#1


19  

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:

在Asp.Net MVC中,您不需要使用WebMethod来装饰您的方法。您只需创建一个Action(这是一个方法)并从中返回一个结果。样品:

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):

在你的视图中,你可以尝试这样的javascript(使用$ .ajax jquery方法 - 参见注释):

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

#2


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.

在MVC中,你不需要[WebMethod]东西 - 你可以有一个常规的控制器动作返回一个ActionMethod(如果你不需要返回值,则返回null)。具有静态方法的WebMethod属性适用于WebForms,而不适用于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.

您在javascript中的网址将是该操作的网址,您可以使用@ Url.Action(“updateOrder”,“Orders”)在Razor中获取该网址,其中“订单”是您的控制器的名称。

#3


0  

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

    确保“url”的格式为page.aspx / updateOrder。

  2. Specify datatype: json

    指定数据类型:json

  3. Ensure your updateOrderJS() is being called.

    确保正在调用updateOrderJS()。

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

    确保contentType:“application / json; charset = utf-8”包含在内。

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

注意:[WebMethod]用于调用webforms方法,而不是MVC。

#4


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.

看起来您将MVC路由的URL放在

标记的action属性中。我看不出那个属性是什么样的,因为你没有发布你的html,但从我看到的那个属性的值可能是错误的。

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

大多数情况下,特定MVC操作的URL是http:// ServerDomain / Path(IfAny)/ ControllerName / ActionName。例如,如果你有一个这样的控制器和动作......

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.

...并且您的ASP.NET应用程序已部署到www.example.com,

标记的action属性中的URL将为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.

当然,ASP.NET MVC中的其他设置可能会更改这些URL,例如global.asax的RegisterRoutes方法中的路由设置,或者如果您的控制器分为区域。如果您的

的URL看起来正确,请在您的ASP.NET应用程序中发布html以及任何相关的控制器路由代码。

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.

如果您的表单位于Razor视图(cshtml文件)中,您可以使用

来生成正确的表单URL。