1

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

0

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.