I am trying to pass an XML string from the HTML/JavaScript client side to the ASP.NET MVC server side. The problem is that the XML string never reaches the server, whereas an ordinary "non-XML" string will be successfully transferred.

The relevant JavaScript code on the client side is the following:

function TransferXmlDataToServer() {
    var sXml = "<Tag>This is an XML test string.</Tag>"
    $.ajax({
        type: "POST",
        url: '@Url.Action("TransferXMLData", "Home")',
        data: { sInputXml: sXml },                             
        dataType: "json",
        success: function(sReturnValue) {
            alert("Value returned from server is: " + sReturnValue);
        },
        error: function() {
            alert("There was an error on the server side");
        }
    })
};

This is the corresponding function in the MVC Home controller on the server side:

public JsonResult TransferXMLData(string sInputXml) {
    // The arguments' name must match those used in the View's Ajax call
    return Json("Success");
}

When the TransferXmlDataToServer is invoked from the client side, the There was an error on the server side message is displayed. I have put some debugging printing statements in the TransferXMLData on the server side that are not invoked, showing that one does not even enter in this function.

On the other hand, when

sXml = "<Tag>This is an XML test string.</Tag>"

is replaced by the following,

sXml = "This is a test string."

everything works as expected.

Additional notes:

  • This was tried with IE11 and Edge.
  • I tried to convert the XML string to Serialized Json prior to sending it to the server, to no avail.

I would greatly appreciate knowing what I am doing wrong.

Thanks a lot.

1 Answer 1

This is because by default asp.net protects against content that looks like HTML mark-up being sent to a controller action un-encoded. You need to decorate your action with the ValidateInputAttribute to let the content through:

[ValidateInput(false)]
public JsonResult TransferXMLData(string sInputXml) 
{
    // The arguments' name must match those used in the View's Ajax call
    return Json("Success");
}