jQuery在Ajax中调用ASP.NET MVC C#中的Action方法 [英] jQuery to call Action Method in ASP.NET MVC C# by Ajax
问题描述
我已经尝试了几个小时才能使这个工作,我真的希望你们中的一个人知道(很多)比这更多。当客户端在文本框中键入时,我想打电话给MVC C#控制器方法名为updateOrder()。理想情况下,我想使用FormCollection访问表单元素(该表单称为createOrder)。
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").
在控制器中,我有:
C#
[WebMethod]
public static void updateOrder(){
string s = "asdf";
}
上面的字符串声明是breakpointed。在视图中,我有一个基本上复制和粘贴的方法,我在stackoverflow上找到:
The string declaration above is breakpointed. In the view, I have a method I basically copy and pasted that I found on stackoverflow:
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;
}
事件很简单:
JavaScript
JavaScript
updateOrderJS();
updateOrderJS()方法触发(使用警报检查),但断点不会。
The updateOrderJS() method fires (checked with an alert), but the breakpoint does not.
推荐答案
在Asp.Net MVC中,你不需要用 WebMethod $ c $来装饰你的方法C>。您只需创建一个Action(这是一个方法)并从中返回一个结果。样本:
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);
}
}
并在中查看
,你可以尝试这样的javascript(使用 $ .ajax jquery方法 - 参见评论):
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');
}
});
这篇关于jQuery在Ajax中调用ASP.NET MVC C#中的Action方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!