简体   繁体   中英

Javascript var with a newline using MVC Model property

I have to set a Javascript variable to equal a property in my MVC model.

I am doing this to detect if any changes were made to a textbox, this is setting the "original" value.

My Javascript code looks like this:

var initVal = '@Model.ReferralHistoryDetail[1].ReferralComments';

I am getting an error, which I assume is due to this containing carriage returns in the comments.

Uncaught SyntaxError: Unexpected token ILLEGAL

The HTML being rendered in this case is putting the closing quote on a newline, and that is the error being shown in the developer console.

For example, the rendered HTML is:

        var initVal = 'blah blah blah
';

What is the proper way to handle this?

您想使用JavaScriptStringEncode命令以JavaScript兼容方式对字符串进行编码。

var initVal = '@HttpUtility.JavaScriptStringEncode(Model.ReferralHistoryDetail[1].ReferralComments)';

You need to create an extension method that replaces the new line character with
tags.

Or use the method HtmlEncode like this:

var initVal = @Html.Raw(HttpUtility.HtmlEncode(@Model.ReferralHistoryDetail[1].ReferralComments).Replace("\n", "<br />"))

If you replace \\n character by \\ , you will have a valid syntax for multiple lines string.

So that should work
var initVal = '@Model.ReferralHistoryDetail[1].ReferralComments.Replace("\\n","\\\\")';

I found other ways to allow multiple line string in javascript, in this answer.

You cannot access Model properties from JavaScript like that, JavaScript cannot do anything with your model.

Create a variable up the page

@{ var value = @Model.ReferralHistoryDetail[1].ReferralComments;

Then access value in javascript, though not sure why you don't just render directly on page why do you need javascript unless I am missing something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM