Search code examples
jqueryasp.net-mvcajaxjsonhtml-encode

MVC, JQUERY, AJAX, HTML-encode JSON response


This question has been asked before, but I must realize, I havn't found the real/best way of doing this!

The issue is, that I want to encode the response I get from the AJAX call in order to prevent Cross-site scripting (XSS) attacks. I have a form with a textbox and submit-button. When submitting, the value is posted to the server and returned to the client. Here i need to html encode the response, as the message e.g. could be " alert('Hello') " etc.

How do I encode item.Message in the following?

View

$(document).ready(function () {

    $("form[action$='SubmitChatMessage']").submit(function () {
        $.ajax({
            url: $(this).attr("action"),
            type: "post",
            dataType: "json",
            data: $(this).serialize(),
            success: function (response) {
                $("#chatMessages").empty();

                var chatMessages = "";
                $.each(response, function (i, item) {
                    chatMessages += '<div>' + item.Message + '</div>';
                });

                $("#chatMessages").html(chatMessages);
                $("#message").val(''); // Clear the textbox value
            }
        });
        return false;
    });
});

<div id="chatContent">
    <% using(Html.BeginForm("SubmitChatMessage", "ProductDetails"))
       {%>
    <%: Html.TextBox("message")%>
    <%: Html.Hidden("productId", Model)%>
    <input type="submit" value="Tilføj" />
    <% }%>
    <div id="chatMessages">
    </div>
</div>

Controller Action

[HttpPost]
[ValidateInput(false)]
public JsonResult SubmitChatMessage(string message, Guid productID)
{

    // 1. Store message in db

    // 2. Fetch messages from db
    List<Message> chats = DB.GetMessages(productID);
    var json = (from c in chats 
               select new {Message = c.Message, CreatedDate = c.Created});

    return Json(json);
}

Hope to get an answer, this is driving me insane! A similar question was given here, but I cant see how to use .text in my case.

UPDATE: Is this really the solution?


Solution

  • Try like this:

    success: function (response) {
        var messages = $('#chatMessages');
        messages.empty();
    
        $.each(response, function (i, item) {
            messages.append(
                $('<div/>', {
                    text: item.Message
                })
            );
        });
    
        $('#message').val(''); // Clear the textbox value
    }