简体   繁体   中英

ASP.NET MVC 4 FormCollection is Empty using Angularjs $Http.post

I'm submitting a form post using Angularjs (1.2.20) to Microsoft ASP.Net MVC 4 :

public ActionResult Save2(FormCollection customer)
{
   //TODO: Do some stuffs...
   return new HttpStatusCodeResult(HttpStatusCode.OK);
}

However, the FormCollection is empty. I know that the data is being sent because if I change it to the following code below (using strongly type CustomerVm ), it works as expected.

public ActionResult Save1(CustomerVm customer)
{
   //TODO: Do some stuffs...
   return new HttpStatusCodeResult(HttpStatusCode.OK);
}

I'm using FormCollection so that I can add ASP.Net anti-forgery token in the data (instead of headers). Below is my custom javascript code. Also you can find the entire code ( Visual Studio ) here

You need to send the request with a content-type of application/x-www-form-urlencoded and encode the request body as such. This is a good start but it's sending the data as JSON.

var data = JSON.stringify(customer);

// FormCollection
$http({
    method: 'POST',
    url: '/Home/Save2',
    //dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset-UTF-8',
    //contentType: 'application/json; charset-UTF-8',
    data: data
});

Turning the object into a URL encoded form is actually pretty complex. Thankfully, Ben Nadel has already created a transformRequestAsFormPost service to do this via a request transformer. You can give it a try by adding in his code and making this change to yours...

myApp.factory('customerSvc', function ($http, transformRequestAsFormPost) {
    return {
        // ...
        save2: function (customer, antiForgeryToken) {
            $http({
                method: 'POST',
                url: '/Home/Save2',
                transformRequest: transformRequestAsFormPost,
                data: 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