简体   繁体   中英

Correct jQuery syntax for doing a $.post with a header (ASP.NET MVC)

I'm working on a ASP.NET MVC project that uses some jQuery on the client side. I have a jQuery call like this, which works correctly:

$.post($('form').attr("action"), $('form').serialize(), function(data){
    // Deal with the data that came back from the ASP.NET MVC controller
}

I want to do the exact same call, except I also want to send in a custom header. I am able to successfully create and send a custom header like this:

var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;

$.ajax({
    url: "/report_observation/" + submitType, 
    cache: false,
    type: "POST",
    data: {
    'viewModel': $('form').serialize(),
    },
    headers: headers,
    success: function (data) {
    // Deal with the data that came back from the ASP.NET MVC controller
    },
    error: function (response) {
    alert("Error: " + response);
    }
});

There are two problems with this second bit of code. One is that I have to make a custom url to go to the correct controller, and I don't know of a way to simply use $('form').attr("action") to automatically go to the correct place.

The second -- and bigger -- problem is that I'm not able to pass over the form data with $('form').serialize() as I could in the one liner $.post example. Doing a @Html.Raw(Json.Encode(Model)) in my Razor cshtml file doesn't send over the model for the whole form, presumably because this code is within a partial view that doesn't know the state of the models in the other partial views that make up this form.

Anyway, I'm thinking there must be an easy way to take this code...

var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;

...and incorporate the headers property into this bit of code:

$.post($('form').attr("action"), $('form').serialize(), function(data){
    // Deal with the data that came back from the ASP.NET MVC controller
}

However, I can't figure out the correct syntax. Any ideas?

OK, I figured it out. The second example can indeed work if the data field looks like this:

data:  $("form").serialize(),

In other words, I had to NOT assign it to the viewModel parameter.

yes, for the second problem use that dev5000 says, and, for the URL, simply get the value for the attribute action fo the form and use it:

var url = $("from").attr("action");
$.ajax({
    url: url, 
...
})

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