我是.NET MVC的新手。我正在尝试对.NET方法进行Ajax调用,但它不起作用。请帮忙。
这是我的Ajax代码:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "userID": $('#confirmation-email-userid').text().toString(), "subject": $('#confirmation-email-subject').text().toString() }),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
这是我在UtilityController中的.Net方法:
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail(string userID, string subject)
{
string destination = db.Users.Where(u => u.Id == userID).Select(u => u.Email).FirstOrDefault();
Task<string> result = new AccountController().SendEmailConfirmationTokenAsync(userID, subject, destination);
return Json(result, JsonRequestBehavior.DenyGet);
}
答案 0 :(得分:2)
尝试删除ajax请求的数据参数中的引号
像这样:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({
userID: $('#confirmation-email-userid').text().toString(),
subject: $('#confirmation-email-subject').text().toString()
}),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
答案 1 :(得分:1)
试试这个,但是如果你使用asp.net mvc,我想你不需要[WebMethod]属性
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail([FromBody] MyModel model)
{
....
}
public class MyModel{
public string userID {get; set;}
public string string subject {get; set;}
}
答案 2 :(得分:0)
我认为您的网址存在问题 使用“ URL:” / Ultility / ResendConfirmationEmail”,” 插入了“ url:“ / Utility / ResendConfirmationEmail”,“
因为您的控制器名称是UtilityController
答案 3 :(得分:0)
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: "{'userID': "+$('#confirmation-email-userid').text().toString()+",'subject': "+$('#confirmation-email-subject').text().toString()+" }",
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
答案 4 :(得分:0)
从您的操作方法中删除 [webmethod] 数据注释,
第二个选项,您正在尝试传递 json 对象,因为您不需要将其转换为字符串。简单地传递对象
它会起作用?