6

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.

i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}

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

    });

and Server-Side 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 part gives me an error: Invalid object passed in and error in System.Web.Script.Serialization.JavascriptObjectDeserializer.

It's like jquery doesnt accept string with html content.what is wrong with my code ?

Lucas Eduardo
  • 11,525
  • 5
  • 44
  • 49
Mr. Lost
  • 63
  • 1
  • 1
  • 4
  • 1
    Is this an internal project? It seems extremely dangerous to provide a user with access to modifying HTML you are serving. – Erik Philips Sep 11 '13 at 02:16
  • well i just wanted to let "users" to make posts like exactly in this site.In this site, when i want to make a post i just click the ASK A QUESTION buttton and a textarea editor will appear. that's what i want to do. it's just appending html content into a new created html file.if it is dangeours i dont know any other way to do that safely – Mr. Lost Sep 11 '13 at 04:22

3 Answers3

17

Pass it like this

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

You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.

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

        });
Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
  • thanks,it works now. JSON.stringify works like magic.im gonna have to read more about Json format – Mr. Lost Sep 11 '13 at 18:43
  • You are welcome. Please read this too. This will help you to do ajax better. http://stackoverflow.com/questions/18711221/sending-key-value-pairs-as-json-to-asmx-service-with-jquery/18733165#18733165 – Subin Jacob Sep 12 '13 at 04:16
  • You can see that a class is created to parse the JSON content. But you can avoid that too using dictionary and anonymous datatypes in c#. To know, just ask! – Subin Jacob Sep 12 '13 at 04:18
  • I get this error: `Uncaught SyntaxError: Invalid or unexpected token` – Si8 Oct 18 '17 at 15:22
11

You can use this

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

and on server end you can decode it to get the html string as

HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Bibhu
  • 4,053
  • 4
  • 33
  • 63
  • it accepted all the content but it killed the html code and it was plain weird code – Mr. Lost Sep 11 '13 at 04:32
  • thanks, but it doesnt change back to the previous html string so it's the same as when i did not include the httputility.urldecode.it's just some weird code. – Mr. Lost Sep 11 '13 at 18:45
2

Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.

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