![](/img/trans.png)
[英]AJAX call in ASP.NET MVC application not calling Action method
[英]jQuery to call Action Method in ASP.NET MVC C# by Ajax
我已经尝试了几个小时来让它工作,我真的希望你们中的一个人比我更了解(很多)。当客户端在文本框中键入时,我想调用 MVC C# 控制器方法称为 updateOrder()。 理想情况下,我想使用 FormCollection 访问表单元素(该表单称为“createOrder”)。
在控制器中,我有:
C#
[WebMethod]
public static void updateOrder(){
string s = "asdf";
}
上面的字符串声明是断点的。 在视图中,我有一个我在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;
}
事件很简单:
JavaScript
updateOrderJS();
updateOrderJS() 方法会触发(通过警报检查),但断点不会。
在 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);
}
}
在您的View
,您可以尝试这样的 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');
}
});
在 MVC 中,你不需要[WebMethod]
东西——你只需要一个常规的控制器操作返回一个ActionMethod
(或者如果你不需要返回值,则为 null)。 带有静态方法的WebMethod
属性用于 WebForms,而不是 MVC。
public ActionMethod updateOrder(MyModel someModel) {
// Do something
return null;
}
您在 javascript 中的 URL 将是该操作的 URL,您可以在 Razor 中使用@Url.Action("updateOrder", "Orders")
该 URL,其中“Orders”是您的控制器的名称。
确保“url”的格式为page.aspx/updateOrder 。
指定datatype: json
确保您的updateOrderJS()
正在被调用。
确保包含contentType: "application/json; charset=utf-8"
。
注意: [WebMethod]
用于调用 webforms 方法,而不是 MVC。
看起来您将 MVC 路由的 URL 放在<form>
标记的action
属性中。 我看不到该属性的样子,因为您没有发布您的 html,但从我所看到的该属性的值可能是错误的。
大多数情况下,特定 MVC 操作的 URL 是http://ServerDomain/Path(IfAny)/ControllerName/ActionName
。 例如,如果你有一个这样的控制器和动作......
public class StackController
{
[HttpPost]
public ActionResult Overflow()
{
return View();
}
}
...并且您的 ASP.NET 应用程序部署到 www.example.com,您的<form>
标记的action
属性中的 URL 将是http://www.example.com/Stack/Overflow
。
当然,ASP.NET MVC 中的其他设置可能会更改这些 URL,例如 global.asax 的RegisterRoutes
方法中的路由设置,或者如果您的控制器被划分为区域。 如果您的<form>
的 URL 看起来正确,请在您的 ASP.NET 应用程序中发布 html 以及任何相关的控制器路由代码。
如果您的表单在 Razor 视图(cshtml 文件)内,您可以使用<form action="@Url.Action({ controller = "ControllerName", action = "ActionName" })" method="post">
来生成正确的表单 URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.