1

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?

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

can you explain what the text:item.Message means here?
@Nima, it uses the .text() method to set the contents of the newly created div and which takes care of properly HTML encoding the value (contrary to the .html() method).
thank you very much. That worked. I can see that the same is mentioned in the "Is this really the solution?" link I have posted in the update section. But thanks, this is not the first time you are helping me with answers :)
1

Alternatively you could use something like HttpUtility.HtmlEncode on the controller's action.

var json = (from c in chats 
           select new {
               Message = HttpUtility.HtmlEncode(c.Message), 
               CreatedDate = c.Created
           });

return Json(json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.