简体   繁体   English

如何在Javascript中使用换行符获取MVC模型数据类型字符串

[英]How to get MVC Model Datatype String with Newline in Javascript

I am attempting to pass the data (type = string) from my MVC model to a javascript funcion but I keep getting an error "Uncaught SyntaxError: Unexpected token ILLEGAL". 我正在尝试将数据(类型=字符串)从我的MVC模型传递给j​​avascript函数,但是却不断收到错误消息“ Uncaught SyntaxError:Unexpected token ILLEGAL”。 I believe this is caused by the newlines in the model data as it only occurs with multi-line strings. 我相信这是由模型数据中的换行符引起的,因为它仅在多行字符串中出现。

The idea is for the user to press the "undo" button/link to reset the text area. 这个想法是让用户按下“撤消”按钮/链接来重置文本区域。

Image: 图片:

在此处输入图片说明

CSHTML: CSHTML:

@Html.TextAreaFor(model => Model.updates[i].body, new { @Class = "txtTextArea floatLeft", @Id = "Edit_" + i.ToString(), @style = "width: 70%;", @Rows = "4", @Cols = "30" })

<a class="textRight EditToLink" onclick="clearInput('Edit_@i.ToString()', '@Html.Raw(Model.updates[i].body)')" id="EditToOneLink_@i.ToString()" href="#" >undo</a>

Javascript Function: Javascript功能:

function clearInput(input, val) {
    if (document.getElementById(input) != null) {
        if (val != null) {
            val.replace(/\r?\n/g, "\r\n");
            document.getElementById(input).value = val;
        }
        else {
            document.getElementById(input).value = "";
        }
    }
}

Similar Question: http://forums.asp.net/t/1741372.aspx?pass+model+parameter+to+javascript+function 相似问题: http : //forums.asp.net/t/1741372.aspx?pass+model+parameter+to+javascript+function

Thanks is advance! 谢谢是前进!

I do a replace(@"\\n", "") on the string. 我在字符串上执行replace(@"\\n", "")

OR 要么

Use JSON.NET JsonConvert.SerializeObject(model.data) 使用JSON.NET JsonConvert.SerializeObject(model.data)

By the way, in CSS to display multiline stuff use this: 顺便说一句,在CSS中显示多行内容的方法如下:

{
    white-space: pre-wrap;
}

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

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