Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor declarative helper used as javascript string

Assuming i have a helper such as:

@helper AddErrorSpan(string error)
{
    <span class="error">@error</span>
}

I run in to issues attempting to call the helper in javascript. For example:

if ($('#YearTextBox').val() == "") 
{
        $('#ErrorDiv').append('@AddErrorSpan("Year field is required.")');
}

This fails and causes a javascript syntax error because the helper returns a newline at the end. This causes the trailing '); to be pushed to the next line causing the syntax error. Is there anything I can do to remedy this easily? Currently the easy solution is to make the helper like this.

@helper AddErrorSpan(string error)
{<span class="error">@error</span>}

Since there's no break before the closing } the new line isn't returned from the helper and there is no javascript syntax error. This is kind of annoying and just ugly to look at. Is there a way to keep the helper from returning the newline when called in my javascript method?

like image 913
Rick Avatar asked Jul 29 '11 16:07

Rick


2 Answers

You need to Javascript-encode the string by calling HttpUtility.JavaScriptStringEncode when calling the helper.

This will escape the newline as \r\n, which will in turn be harmlessly swallowed by the HTML parser.

$('#ErrorDiv').append('@HttpUtility.JavaScriptStringEncode(AddErrorSpan("Year field is required.").ToString())');
like image 181
SLaks Avatar answered Sep 29 '22 07:09

SLaks


You can also use AjaxHelper.JavaScriptStringEncode:

@Ajax.JavaScriptStringEncode(value)

Or declare a helper to make it more succinct:

@helper JsEncode(string value) {
    @(HttpUtility.JavaScriptStringEncode(value))
}
like image 40
Chris Fulstow Avatar answered Sep 29 '22 05:09

Chris Fulstow