Razor declarative helper used as javascript string

Assuming I have an assistant, for example:

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

I ran into problems trying to call helper in javascript. For instance:

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

This does not work and causes a javascript syntax error because the helper returns a new line at the end. This causes trailing to ');be wrapped to the next line, resulting in a syntax error. Is there anything I can do to fix this easily? For now, the easy solution is to make an assistant this way.

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

}, javascript. . , javascript?

+5
2

Javascript- , HttpUtility.JavaScriptStringEncode .

, \r\n, , , HTML.

$('#ErrorDiv').append('@HttpUtility.JavaScriptStringEncode(AddErrorSpan("Year field is required.").ToString())');
+4

AjaxHelper.JavaScriptStringEncode:

@Ajax.JavaScriptStringEncode(value)

, :

@helper JsEncode(string value) {
    @(HttpUtility.JavaScriptStringEncode(value))
}
+1

All Articles