javascript 在 MVC4 中使用 Ajax 调用 Action 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18123381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call an Action method using Ajax in MVC4
提问by tishantha
Action method doesn't fire in my code. Can you please show me the error. :)
Action 方法不会在我的代码中触发。你能告诉我错误吗。:)
here is the code..
这是代码..
<script type="text/javascript">
$("#btnSave").click(function () {
var ContactID = $("#txtContactId").val();
var Company = $("#txtCompany").val();
var Status = $("#cmbStatus").val();
var IsActive = $("#IsActive").is(':checked');
var Comments = $("#txaComments").val();
var Country = $("#cmbCountry").val();
var Address1 = $("#txtAddress1").val();
var Address2 = $("#txtAddress2").val();
var City = $("#txtCity").val();
var State = $("#txtState").val();
var PostalCode = $("#txtPostalCode").val();
var VatNo = $("#txtVatNo").val();
var RegNo = $("#txtRegNo").val();
var Phone = $("#txtPhone").val();
var Email = $("#txtEmail").val();
$.ajax({
url: "Customer/InsertCustomer",
data: {
'ContactID': ContactID,
'Company': Company,
'Status': Status,
'IsActive': IsActive,
'Comments': Comments,
'Country': Country,
'Address1': Address1,
'Address2': Address2,
'City': City,
'State': State,
'PostalCode': PostalCode,
'VatNo': VatNo,
'RegNo': RegNo,
'Phone': Phone,
'Email': Email
},
dataType: "json",
type: 'POST',
success: function (data) {
alert("Successfully Inserted!");
},
error: function () {
alert("error");
}
});
});
Here is the Action method..
这是Action方法..
public ActionResult InsertCustomer(string ContactID, string Company, int Status, bool IsActive, string Comments, int Country, string Address1, string Address2, string City, string State, string PostalCode, string VatNo, string RegNo, string Phone, string Email)
{
bool process = false;
return Json(process, JsonRequestBehavior.AllowGet);
}
回答by Andriy Gubal
You need to set [HttpPost] attribute:
您需要设置 [HttpPost] 属性:
[HttpPost]
public ActionResult InsertCustomer(string ContactID, string Company, int Status, bool IsActive, string Comments, int Country, string Address1, string Address2, string City, string State, string PostalCode, string VatNo, string RegNo, string Phone, string Email)
{
bool process = false;
return Json(process, JsonRequestBehavior.AllowGet);
}
回答by YD1m
It can be an issue with the wrong url. Use Url.Action()
helper:
这可能是错误网址的问题。使用Url.Action()
帮手:
$.ajax({
url: "@Url.Action("InsertCustomer", "Customer")",
Also you can check your browser console for error details.
您也可以检查浏览器控制台以获取错误详细信息。
Btw, if you want to send values from the form you can use the jquery .serializeArray()
method:
顺便说一句,如果你想从表单发送值,你可以使用 jquery.serializeArray()
方法:
$.ajax({
url: "@Url.Action("InsertCustomer", "Customer")",
data: $('form').serializeArray()