6

I am trying to post some data with jQuery Ajax, but the parameters in my Ajax method are null.

This is simple test to send data:

 var dataPost = { titel: 'titel', message: 'msg', tagIds: 'hello' };
        jQuery.ajax({
            type: "POST",
            url: "Create",
            contentType: 'application/json; charset=utf-8',
            data: $.toJSON(dataPost),
            dataType: "json",
            success: function(result) {
                alert("Data Returned: ");
            }
        });

And my Ajax method looks like this:

[HttpPost]
public ActionResult Create(string title, string message, string tagIds)
{... }

There is something basic wrong with the data I send, but I can't figure out what. All the time the title, message and tagIds are null, so there is something wrong with the encoding, I just don't know what.

Optimally the parameter tagIds should be an array or list of guids.

Note: The jQuery.toJSON is this plugin

2 Answers 2

15

The Create controller action doesn't expect parameters to be JSON serialized so you don't have to. Try passing them directly instead:

var dataPost = { titel: 'titel', message: 'msg', tagIds: 'hello' };
jQuery.ajax({
    type: "POST",
    url: "Create",
    data: dataPost,
    dataType: "json",
    success: function(result) {
        alert("Data Returned: ");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks apparently the content type made more trouble than good.
Same problem, I couldn't figure out why the model binding wasn't working for a simple string... I had the contentType set to json. After removing it, worked great.
0

We don't need the contentType: 'application/json; charset=utf-8', and $.toJSON

Here is the code makes me happy!

 $(function () {
        $("#btnSumbit").click(function () {
            $('#results').hide();
            $('#loadingmessage').show();
            var a = $("#query").val();

            $.ajax({
                type: "POST",
                url: "/Search/Index",
                data: ({ query: a }),
                datatype: "json",
                success: function (data) {
                    $('#results').empty();
                    for (var i = 0; i < data.length; i++) {
                        var div = "<div>" + data[i].Name + "</div>";
                        $("#results").append(div);

                    }
                    $('#loadingmessage').hide();
                    $('#results').show();
                },
                failure: function (errMsg) {
                    $('#loadingmessage').hide();
                    alert(errMsg);
                }
            });
        });
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.