trying to make an AJAX call to a c# controller
my controller
[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 });
}
}
my ajax call:
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);
}
});
}
when i use data: { 'email': email },
and put a breakpoint on my controller method, it doesnt hit it at all.
but i was to do data: Json.stringify(email),
the breakpoint is hit, but the email value being passed through is null
any ideas?
CodePudding user response:
You are posting an object
$.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);
}
});
Change the parameter as an object.
[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; }
}