1

I want to pass Json data to Controller by Ajax (I had refered to AntiForgery and JSON incompatible? before) and this is my code:

Ajax:

var self = this;
self.Url = ko.observable();
self.Description = ko.observable();
self.ValueName = ko.observable();
self.MatchRegex = ko.observable();
self.__RequestVerificationToken = ko.observable('@Html.AntiForgeryTokenValueOrchard()');

self.Xpaths = ko.observableArray([
    { Name: 'RootXPath', Xpath: '', Regex: '', isRootXPath: true }
]);

self.addRow = function () {
    self.Xpaths.push({ Name: '', Xpath: '', Regex: '', isRootXPath: false });
};

self.removeRow = function () {
    if (this.name == 'RootXPath')
        return;
    self.Xpaths.remove(this);
};
self.executeExtractScript = function () {
var myValues = JSON.stringify(ko.toJS(self));
$.ajax({
    url: '@Url.Action("EExtractScriptTemp", "Home", new { area = "Crawler" })',
    type: 'POST',
    data: myValues,
    contentType: 'application/json; charset=utf-8',
    success: function () {
        $(".result").html("Success");
        runEffect();
    },
    error: function () {
        $(".result").html("Error");
        runEffect();
    }
});

};

My Controller

[HttpPost]
public ActionResult EExtractScriptTemp(ExtractScriptTempModels objectJSon) {
   return null;
}

And the real value of myValues is (by inspecting element in Chrome):

"{"__RequestVerificationToken":"6ygUGMe1PER7FizLBqCDJLcSfp9zuA4dcRyUHCwVwkWzOTO0AiRF8QRSDwoqRI-SD9FfiFvF-jozFKL10HS21xTBlRP4EndYbmGhPSX_Kuk1F0r0swYnGZZxZdy793eQxfmkvjIUtnwdLtrg0q8zhFdZNJBvmiPA6dC57prmw1c1","Xpaths":[{"Name":"RootXPath","Xpath":"","Regex":"","isRootXPath":true}]}"

However, it still rose error

{"The required anti-forgery form field \"__RequestVerificationToken\" is not present."}

I have tried to use both @Matthew's method and @Giscard Biamby's but it was work no longer.

What's my problem ? Thanks very much !

Community
  • 1
  • 1
Leo Le
  • 815
  • 3
  • 13
  • 33

2 Answers2

0

Don't stringify your payload. Let jQuery take care of sending the data. There are examples in the existing code. Search for $.post( in the Orchard code. You'll find one in Orchard.MediaPicker.

Bertrand Le Roy
  • 17,731
  • 2
  • 27
  • 33
  • I will try to solve it according to your advice and reply result later. Thanks @Bertrand Le Roy – Leo Le Jun 08 '13 at 04:36
0

try to add [ValidateAntiForgeryToken] to head of the function

[HttpPost]
[ValidateAntiForgeryToken] 
public ActionResult EExtractScriptTemp(ExtractScriptTempModels objectJSon) {
   return null;
}

in client i send data like this

//find the Token
 var token = $('input[name="__RequestVerificationToken"]').val();

     data: {
    "someText": "Text",
      "__RequestVerificationToken": token
        },

After this changes error is gone (in my case)

Vladimir Potapov
  • 2,347
  • 7
  • 44
  • 71