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?
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())');
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With