use*_*057 8 javascript c# ajax asp.net-mvc jquery
我已经尝试了几个小时才能使这个工作,我真的希望你们中的一个人知道(很多)比这更多关于这个.当客户端在文本框中键入时,我想调用MVC C#控制器名为updateOrder()的方法.理想情况下,我想使用FormCollection访问表单元素(该表单称为"createOrder").
在控制器中,我有:
C#
[WebMethod]
public static void updateOrder(){
string s = "asdf";
}
Run Code Online (Sandbox Code Playgroud)
上面的字符串声明是breakpointed.在视图中,我有一个基本上复制和粘贴的方法,我在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;
}
Run Code Online (Sandbox Code Playgroud)
事件很简单:
JavaScript的
updateOrderJS();
Run Code Online (Sandbox Code Playgroud)
触发updateOrderJS()方法(使用警报检查),但断点不会触发.
Fel*_*ani 20
在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);
}
}
Run Code Online (Sandbox Code Playgroud)
在你的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');
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34477 次 |
| 最近记录: |