简体   繁体   中英

Ajax query string not being posted to ASP.NET controller

I have this Ajax function:

UpdateFIConfig: function ($appForm) {

    var valid = $appForm.valid();
    //if not valid the validate plugin will take care of the errors
    if (valid) {

        $appForm.serialize();
        $.ajax({
            url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
            data: $appForm,
            dataType: 'application/json',
            cache: false,
            type: 'POST',
            success: function (data) {
                if (data.Error) {
                    cc.jqUtils.openDialog(data.ErrorDescription, 'Error', 'OK', null, null, null);
                } else {
                    window.location.href = '/IdentifiConfig/DefaultConfiguration';
                }
            }
        });

    }
},

Which serializes data sent from my view into a query string. I know the data is serialized correctly because I have viewed the string with console.log($appForm) , and it's correct.

However, my controller never receives the query string. I have removed a lot of code, but this is basically what the controller function looks like:

 [HttpPost]
 public ActionResult UpdateFIConfig(string query)
 {
     NameValueCollection nvc = HttpUtility.ParseQueryString(query);

     System.Diagnostics.Debug.WriteLine(nvc);
 }

I receive a null pointer on the line which tries to parse the query string, and I don't know why. Any help?

我在我的项目中有同样的事情ajax唯一不同的是我不使用dataType而是contentType:“application / json; charset = utf-8”

data: "{'query' : '" + $appForm + "'}"

This bit:

$appForm.serialize();

Returns a string that you're never using. serialize won't actually modify the form. You should assign it to a variable and pass that up instead:

var data = $appForm.serialize();

$.ajax({
    url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
    data: data,
    /* etc */
});

There is probably a better way, but I get around this annoyance by accepting an Object with a string property instead of just a string. So do something like:

 [HttpPost]
 public ActionResult UpdateFIConfig(MyTypeWithQry query)
 { ...

and

    $.ajax({ url: '/IdentifiConfig/DefaultConfiguration/UpdateFIConfig',
             data: { 'query' : $appForm },
             dataType: 'application/json',
...

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