Recently, I faced an issue while sending an HTML string as a parameter to the Controller action. What I wanted was to have two textareas and a button on my View. And then, get the values from textareas and send it to the Controller.
Then, I was going to save these values to a file at the specific location (like JS, HTML, CSS, Txt), and if the file was already there at the location, then read that file and show data in the respective textarea.
What problem did I face?
When I tried to send a string which had HTML tags like '<br>, <b>xxxxxxx</b>', I used an AJAX call to send the data from View to Controller as below.
- function SaveDataToFile() {
- var JsCode = $('#textarea1').val();
- var JsCode2 = $('#textarea2').val();
- $.ajax({
- type: "POST",
- url: "@Url.Action("
- xxxAction ", "
- xxController ")",
- datatype: "JSON",
- data: {
- JsCode: JsCode,
- FileName: xxx,
- JsCode2: JsCode2,
- yyy: yyy
- },
- beforeSend: function() {
- alert("Before send to controller");
- },
- success: function() {
- alert("Success");
- setTimeout(function() {
- location.reload();
- }, 4000);
- },
- });
- }
The above function is a JS function and it will work absolutely fine if JsCode/ JsCode2 variables have plane text
(i.e., no HTML tags in it).
If in those variables you have HTML tags ('<br>, <b>xxxxx</b>, <h1>xxxx</h1>'), then it will not give you any error in console window but it goes in the success of that AJAX method and shows alert as "Success".
This happens because while sending a parameter to the controller (in my above case, there are 4 parameters), the AJAX call will convert it to the JSON format because in the variable (JsCode/JsCode2), it will have HTML code it will not be able to convert to JSON format.
The value in Textarea as,

Dinesh GabhanePosted Jan 15, 2019, 1:14 AM
Nice and very helpful, thanks for sharing.
Mahesh NikamPosted Jan 14, 2019, 11:37 PM
Thanks Omkar sir. It helped me a lot. I was facing the same issue. You saved my time.