5

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?

0

2 Answers 2

4

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

2 Comments

Verbose :(. Why does it have to be so verbose.
@Raynos: If you want to, you can make a helper with a shorter name that calls this method.
1

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))
}

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.