JQuery将NULL值传递给Controller

时间:2013-06-03 13:55:41

标签: jquery asp.net-mvc

我正在尝试使用JQuery检查数据库中是否存在电子邮件。目前,我通过$ajax请求发送电子邮件:

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

我的控制器得到它:

[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; }
        }

但是email的值总是为空。谁能指出我哪里出错了?我是MVC的新手

3 个答案:

答案 0 :(得分:1)

在序列化表单时,您使用JSON.stringify两次。

这将导致错误的请求,例如:

JSON.stringify({x: 5, y: 6}); //"{"x":5,"y":6}"
JSON.stringify(JSON.stringify({x: 5, y: 6})); //""{\"x\":5,\"y\":6}""

<强>更新

我们从讨论中了解到,问题是发送的数据与请求标头之间不匹配:对于contentType: "application/json;charset=utf-8",,表单的值需要正确序列化。调用JSON.stringify($(this).serialize());表单数据后,作为JSON对象发送,没有包含带urlencoded表单数据的字符串的名称。对于带有表单数据的常规帖子,contentType标题需要是“application / x-www-form-urlencoded; charset = utf-8”,如果数据为$(this),将由JQuery设置。 serialize()所以正确的方式是,BrunoLM sugessted

....
$.ajax({
        type: "POST",
        url: "/Home/AddEmail", //without setting the contentType
        data: $(this).serialize(),
        dataType: "json", 
        success: function(data) {
...

答案 1 :(得分:0)

您正在使用JSON.stringify两次,实际上您只需要

data: $(this).serialize()

Here is a working example on jsFiddle

答案 2 :(得分:0)

试试这个:

var postData = { email: { email: $('#email').val() } };