4

Jquery ajax 发布请求将 null json 对象发布到 mvc 控制器。知道为什么会这样吗?

干杯

这是我的模型

public class CommentModel
    {
       public string EmailAddress { get; set; }
       public string Name { get; set; }
       public int ActivityId { get; set; }
       public string CommentText { get; set; }

    }

控制器

 [HttpPost]
        public ActionResult Index(CommentModel commentModel)
        {

            int i = commentModel.ActivityId;
            string k = commentModel.CommentText;

          return View();
        }

jQuery

$("#CommentForm").submit(function () {

        var formDataAsJson = GetFormDataAsJson();

        $.ajax({
            url: $(this).attr("action"),
            dataType: 'json',
            type: "POST",
            data: JSON.stringify({ commentModel: formDataAsJson }),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#commentsection").append(data);
            }
        })
    });

function GetFormDataAsJson() {

    var emailInput = $("#InputEmailAddress").attr("value");
    var name = $("#InputName").attr("value");
    var comment = $("#some-textarea").attr("value");
    var activityid = parseInt($("#ActivityID").attr("value"));

    var formObject = {
        EmailAddress: emailInput,
        Name: name,
        ActivityId: activityid,
        CommentText:comment
    }

    return formObject;
}
4

2 回答 2

5

如果您使用强类型助手,mvc 将其转换为您的模型。您不需要创建 js 模型。

强类型视图

@model CommentModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1" }))
{
    @Html.TextBoxFor(x => x.EmailAddress)
    @Html.TextBoxFor(x => x.Name)
    ...
}

脚本

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                beforeSend: function () {

                },
                complete: function () {

                },
                success: function (result) {

                },
                error: function () {

                }
            });
        }
        return false;
    });
});

控制器

[HttpPost]
public ActionResult Index(CommentModel commentModel)
{
    int i = commentModel.ActivityId;
    string k = commentModel.CommentText;

    return View();
}

相同的问题和另一个建议

于 2013-02-04T10:08:04.083 回答
0

只需添加:

return false;

在提交功能结束时。

于 2013-02-04T10:25:01.073 回答