通过AJAX发送到控制器的字符串参数未命中



尝试对c#控制器进行AJAX调用

我的控制器

[HttpPost]
public JsonResult checkEmail(string email)
{
var emails = emails.GetByEmail(email);
if (emails != null)
{
return Json(new { success = false });
} else {
return Json(new { success = true });
}
}

我的ajax调用:

var checkEmails= function (email) {
/* call the save endpoint */
console.log(email);
$.ajax({
url: '@Url.Action("checkEmail")',
type: 'POST',
data: { 'email': email },
contentType: "application/json; charset=utf-8",
async: true,
success: function (response) {
if (response.success) {
console.log('doesnt exist');
} else {
AlreadyExists();
}
},
error: function (xhr, x, y) {
console.error('failed', xhr, x, y);
}
});
}

当我使用data: { 'email': email },

并在我的控制器方法上设置一个断点,它根本没有命中它。

但我要做data: Json.stringify(email),

断点被命中,但正在传递的电子邮件值为空

有什么想法吗?

您正在发布对象

$.ajax({
url: '@Url.Action("checkEmail")',
type: 'POST',
data: JSON.stringify({ 'email': email }),
contentType: "application/json; charset=utf-8",
async: true,
success: function (response) {
if (response.success) {
console.log('doesnt exist');
} else {
AlreadyExists();
}
},
error: function (xhr, x, y) {
console.error('failed', xhr, x, y);
}
});

将参数更改为对象。

[HttpPost]
public JsonResult checkEmail(CheckEmailInput input)
{
var emails = emails.GetByEmail(input.Email);
if (emails != null)
{
return Json(new { success = false });
} else {
return Json(new { success = true });
}
}
public class EmailInput
{
public string Email { get; set; }
}

最新更新