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

string parameter sent via AJAX to controller not hitting

正在尝试 AJAX 调用 c# 控制器

我的控制器

[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),

断点已命,但传递的email值为null

有什么想法吗?

您正在发布一个对象

$.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; }
}