简体   繁体   中英

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM