简体   繁体   English

使用MVC Model属性的带有换行符的Javascript var

[英]Javascript var with a newline using MVC Model property

I have to set a Javascript variable to equal a property in my MVC model. 我必须将Javascript变量设置为等于我的MVC模型中的属性。

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: 我的Javascript代码如下所示:

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. 在这种情况下,呈现的HTML将结束引号放在换行符上,这就是在开发人员控制台中显示的错误。

For example, the rendered HTML is: 例如,呈现的HTML为:

        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: 或使用像这样的HtmlEncode方法:

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. 如果将\\n字符替换为\\ ,则对于多行字符串将具有有效的语法。

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. 我在答案中找到了其他方法来允许JavaScript中的多行字符串。

You cannot access Model properties from JavaScript like that, JavaScript cannot do anything with your model. 您不能通过这样的JavaScript访问模型属性,JavaScript无法对模型执行任何操作。

Create a variable up the page 在页面上创建一个变量

@{ var value = @Model.ReferralHistoryDetail[1].ReferralComments; @ {var值= @ Model.ReferralHistoryDe​​tail [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 然后访问javascript中的值,尽管不确定为什么不直接在页面上呈现,为什么需要javascript,除非我遗漏了一些东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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