使用Jquery Ajax将html字符串传递给服务器端

我在这个网站上看到很多答案对我有很大的帮助,但在这个问题上,我需要请大家帮帮我。

我有一个textarea作为Html编辑器将html内容传递给服务器并将其附加到新创建的Html页面(用于用户POST等),但jquery或ASP.NET不接受jquery通过数据传递的Html内容: {}

– 对于Jquery:

$("#btnC").click(function (e) { e.preventDefault(); //get the content of the div box var HTML = $("#t").val(); $.ajax({ url: "EditingTextarea.aspx/GetValue", type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String success: function (msg) { alert(msg.d); }, error: function (type) { alert("ERROR!!" + type.responseText); } }); 

和服务器端ASP.NET:

 [WebMethod] public static string GetValue(string num) { StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true); sw.WriteLine(num); sw.Close(); return num;//return what was sent from the client to the client again }//end get value 

Jquery部分给出了一个错误:传入的无效对象和System.Web.Script.Serialization.JavascriptObjectDeserializer.中的错误System.Web.Script.Serialization.JavascriptObjectDeserializer.

这就像jquery不接受带有html内容的字符串。我的代码有什么问题?

像这样传递它

 JSON.stringify({'num':HTML}); 

您必须正确地将内容字符串化为JSON。 HTML可能包含会使JSON表示法无效的synatax。

 var dataToSend = JSON.stringify({'num':HTML}); $.ajax({ url: "EditingTextarea.aspx/GetValue", type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: dataToSend , // pass that text to the server as a correct JSON String success: function (msg) { alert(msg.d); }, error: function (type) { alert("ERROR!!" + type.responseText); } }); 

你可以用它

 var HTML = escape($("#t").val()); 

在服务器端,您可以解码它以获取html字符串

 HttpUtility.UrlDecode(num, System.Text.Encoding.Default); 

确保JSON.stringify,dataType:“json”和contentType:“application / json; charset = utf-8” ,在ajax调用中。

  [HttpPost] public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring) { retrun view(); } $.ajax({ url: '/Controller/ActionMethod', type: "POST", data: JSON.stringify({ para1: titletext, para2: datetext, para3: interchangeNbr.toString(), htmlstring : messageText.toString() }), dataType: "json", contentType: "application/json; charset=utf-8", cache: false, success: function successFunc(data) { }, error: function errorFunc(jqXHR) { $('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show(); } });