I am trying to check if an email exists in a DB using JQuery. Currently, I am sending the email through an $ajax request:
$(".newsletter form").submit(function (event) {
event.preventDefault();
var postData = JSON.stringify($(this).serialize());
var status = $(".newsletter p");
status.removeClass('shake');
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/Home/AddEmail",
data: JSON.stringify(postData),
dataType: "json",
success: function(data) {
if (data == "success")
status.html("Thanks for your interest! We will let you know.").slideDown();
else if (data == "subscribed")
status.toggleClass('shake').html("This email is already subscribed.").slideDown();
else if (data == "invalid")
status.toggleClass('shake').html("This email is invalid.").slideDown();
else if (data == "noValue")
status.toggleClass('shake').html("No email specified.").slideDown();
else
status.toggleClass('shake').html("Oops, something went wrong!").slideDown();
},
error: function () {
status.toggleClass('shake').html("Oops, something went wrong!").slideDown();
}
});
});
And my controller gets it by:
[HttpPost]
public JsonResult AddEmail(EmailA email)
{
string returnMessage = "success";
if (string.IsNullOrEmpty(email.ToString()))
{
return Json("noValue");
}
try
{
SqlConnection sqlConn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ICECONNSTRING"].ConnectionString);
sqlConn.Open();
string sSQL = "SELECT COUNT(em_email) FROM v2_email WHERE em_email = @email";
SqlCommand sqlCommand = new SqlCommand(sSQL, sqlConn) { CommandType = CommandType.Text };
sqlCommand.Parameters.Add(new SqlParameter("@email", SqlDbType.NVarChar, 50)).Value = email;
int count = (int)sqlCommand.ExecuteScalar();
if (count == 0)
{
return Json("subscribed");
}
}
catch (Exception es)
{
Console.Write(es.Message);
return Json("error");
}
return Json(returnMessage);
}
[Serializable]
public class EmailA
{
public string email { get; set; }
}
But the value for email is ALWAYS null. Can someone point out where I'm going wrong? I'm new to MVC
JSON.stringifytwice? and whatinputsyourformcontains? also there's no need to useserializehere.JSON.stringifywas just to force the data (thought it may help). I'm using a template which I HAVE to stick to. When I placealert(postData)I get"email=whatever"