4

Jquery ajax post request is posting null json object to mvc controller. any idea why this could be?

Cheers

Here is my model

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

    }

Controller

 [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;
}
Raju Kumar
  • 1,255
  • 3
  • 21
  • 39
  • Why dont use `data: $('#formId').serialize()` ? OR `data: JSON.stringify(formDataAsJson),` – AliRıza Adıyahşi Feb 04 '13 at 09:56
  • Hi. trying to learn json i thought this exercise would be a good start . But it seems to be taking to long. – Raju Kumar Feb 04 '13 at 09:59
  • When you use strongly-typed helpers in your view you directly post your form in ajax data like: `data: $('#formId').serialize()` – AliRıza Adıyahşi Feb 04 '13 at 10:01
  • JSON.stringify(formDataAsJson) have tried doesn't seem to work either. This problem occurs randomly... when i use chrome debugger the values are posted as expected but when you run it without debugger the values specified to the controller are all null. – Raju Kumar Feb 04 '13 at 10:02

2 Answers2

5

If you use strongly-typed-helper, mvc convert it to your model. You dont need to create js model.

strongly-typed view

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

script

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

Controller

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

    return View();
}

SameQuestion And Another Suggestion

Community
  • 1
  • 1
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
0

just add:

return false;

At the end of your submit funciton.

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130