Joel Etherton
Joel Etherton

Reputation: 37543

How do you add a single quote for javascript in an Html.TextBoxFor method?

I am attempting to add a javascript method as a custom attribute in an Html.TextBoxFor method like this:

<%: Html.TextBoxFor(model => model.DateCreated, new { size="15", onfocus="myObject.myFunction(this, 'DateCreated');return false;"}) %>

The problem I'm experiencing is that the single quote characters are being html encoded, which is an expection I have of the <%:. Is there a way to prevent the html encoding for just that piece (like using a \ to escape characters in strings)? Is there a different method of adding this custom attribute? Or am I just flat out doing this wrong?

Upvotes: 1

Views: 4449

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039190

Even if the quotes are being encoded your javascript should work. For example the following snippet alerts the correct text:

<%: Html.TextBox("DateCreated", "", new { onclick="alert('DateCreated');return false;"}) %>

Another way to achieve this is to use unobtrusive javascript and not mix markup with script:

<%: Html.TextBoxFor(model => model.DateCreated, new { size="15", id="date" }) %>

and then in a separate javascript file using jquery:

$(function() {
    $('#date').focus(function() {
        myObject.myFunction(this, 'DateCreated');
        return false;
    });
});

Upvotes: 2

Levi
Levi

Reputation: 32828

The default encoder in .NET 4 encodes characters it deems to be potentially unsafe, including ', ", &, <, and >. However, this encoding should not affect the execution of the Javascript snippet you're trying to include, since the browser will automatically turn the &#39; back into the ' character before passing it to the Javascript parser. If this is still negatively affecting your application, please respond so that we can consider getting an official bug filed.

If you want, you can change the default encoder used by ASP.NET to one of your own creation. Phil outlined at http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx the steps needed to hook up the Anti-XSS encoder. But if you wanted, you could make a custom HttpEncoder that encoded everything except the ' character by following the same basic steps.

Upvotes: 1

Related Questions