使用$ .ajax将XML发布到MVC Controller方法 [英] Using $.ajax to POST XML to MVC Controller method
问题描述
我有一个像这样的简单控制器功能:
I have a simple controller function like this:
<HttpPost>
Function SaveXML(payload As String) As Boolean
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return True
Else
Return False
End If
End Function
我是这样从JavaScript调用的:
Which I'm calling from JavaScript like this:
function SaveXML() {
var payload = '<?xml version="1.0" encoding="utf-8"?><data>XML_GOES_HERE</data>';
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "text/xml",
data: payload
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
}
我将 JQuery文档上的示例用作基础,并提供一些建议来自此处,此处.我已经尝试过使用processData: false
和不使用processData: false
的情况,这没有什么区别.
I'm using the example on the JQuery documentation as a base with some advice from here, here, and here. I've tried it with and without processData: false
and it makes no difference.
当调用Controller方法时,有效负载为null
. 如果我使用一些非常相似的代码发布一个简单的字符串,那么一切效果很好.通过$.ajax
将XML发布到Controller到底需要做什么?问题出在JavaScript还是Controller端?
When the call comes in to the Controller method the payload is null
. If I post a simple string using some very similar code everything works fine. What precisely needs to be done in order to post XML to a Controller via $.ajax
? Is it at the JavaScript or Controller end that the problem lies?
推荐答案
我最终设法找到了一些提示,最终得到了以下代码:
I eventually managed to find some hints on this and ended up with the following code:
$.ajax({
url: "/Data/SaveXML/",
type: "POST",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ payload: payload })
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
关键区别在于,将contentType
设置为application/json
,将数据转换为对象,然后通过JSON.stringify
方法运行该对象,以确保不适合
The crucial differences are that the contentType
is set to application/json
, the data is turned into an object which is then run through the JSON.stringify
method to make sure that the various characters that are unsuitable for a querystring
can be sent without failing.
这篇关于使用$ .ajax将XML发布到MVC Controller方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!