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

时间:2013-09-11 02:05:19

标签: c# jquery asp.net ajax

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

我有一个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.

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

3 个答案:

答案 0 :(得分:13)

像这样传递

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

        });

答案 1 :(得分:8)

您可以使用此

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

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

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

答案 2 :(得分:2)

确保 JSON.stringify,dataType:" json" and,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();
            }
        });