rksprst
rksprst

Reputation: 6631

ASP.NET MVC $.ajax POST doesn't submit correctly

In javascript I have the following:

$.ajax({
        url: "/ajax/test",
        type: "POST",
        dataType: "html",
        data: '{"keyword" : "' + $('#tbxBrand').val() + '", "projectguid" : "<%= thisProject.ProjectGuid.ToString() %>", "userguid" : "<%= thisUser.UserGuid.ToString() %>"}',
        beforeSend: function() { },
        success: function(data) {
            alert(data);
        }
    });

In the controller I have:

public ActionResult Test()
    {
        string keyword = Request.Form["keyword"];
        return new JsonResult { Data = keyword };
    }

However, the Request.Form does not contain the correct keys. In fact, the Request.Form comes out as which seems incorrect:

Request.Form = {%7b%22keyword%22+%3a+%22data%22%2c+%22projectguid%22+%3a+%22cedce659-fd91-46c8-8f69-e527a38cffc2%22%2c+%22userguid%22+%3a+%2252ff20ab-cdf1-4dae-b539-645b6bf461a7%22%7d}

I can't figure out what is wrong here. Can anyone help?

Thanks!

Upvotes: 2

Views: 995

Answers (2)

tvanfosson
tvanfosson

Reputation: 532435

Don't quote the data. An object will be converted to a query string. If you use a string it needs to be in query string format. Also, I think you'll find it better to use single quotes around the tags. This will allow you to use double quotes inside the tags if needed.

$.ajax({
    url: "/ajax/test",
    type: "POST",
    dataType: "html",
    data: {
           "keyword" :  $('#tbxBrand').val(),
           "projectguid" : '<%= thisProject.ProjectGuid.ToString() %>',
           "userguid" : '<%= thisUser.UserGuid.ToString() %>'
          },
    beforeSend: function() { },
    success: function(data) {
        alert(data);
    }
});

Upvotes: 2

griegs
griegs

Reputation: 22760

I use this;

    function postComment(id) {
    var commentText = jQuery.trim($("#textbox" + id.toString()).val());

    $.post("/jQueryTests/jQueryAddMessageComment", { commentText: commentText }, function(newComment) {
        $("#divComments" + id.toString()).html(newComment);
    });
}

then in c#

        public ActionResult jQueryAddMessageComment(string commentText)
    {
        //postComment
        return PartialView("commentList", new FormViewModel { LastComment = commentText });
    }

I don't use Request.Form as the data should be passed as a parameter to your c# method.

Upvotes: 2

Related Questions