简体   繁体   English

asp.net mvc textarea vs jQuery中换行符的字符数

[英]Character count for newline in asp.net mvc textarea vs jQuery

I'm working on a ASP.NET MVC web application. 我正在研究ASP.NET MVC Web应用程序。 I have a textarea in the view and it's binded to a model which has maximum length of 1000. 我在视图中有一个textarea,它绑定到一个最大长度为1000的模型。

//Html:
@Html.TextAreaFor(model => model.Description, 12, 50, new { @class = "form-control", @placeholder = "Mandatory" })

//Model class:
[Required]
[DisplayName("Event Description")]
[MaxLength(1000, ErrorMessage = "Maximum {1} characters.")]
public string Description { get; set; }

I'm also using jQuery to display a message for the user so that they know how many characters are left to enter: 我也使用jQuery为用户显示一条消息,以便他们知道要输入多少个字符:

    $('#Description').keyup(function () {
        var maxlen = 1000;
        var count = $(this).val().length;
        var charLeft = maxlen - count;
        var string = charLeft + " chracters left"
        if (count > maxlen) {
            this.value = this.value.substring(0, maxlen);
        }
        else {
            $("#descriptionCharCount").text(string);
        }
    });

I found that when there's a new line entered, ASP.NET will insert 2 spaces and therefore increase the character count by 2. But jQuery only increase by 1. This resulting a mismatch. 我发现当输入一个新行时,ASP.NET将插入2个空格,因此将字符数增加2.但jQuery只增加1.这导致不匹配。 How do I solve this problem? 我该如何解决这个问题?

Why it happens: Windows uses two characters ( \\r\\n ), to represent a new line, whereas some browsers only use one of these characters ( \\n ). 为什么会发生这种情况:Windows使用两个字符( \\r\\n )来表示新行,而某些浏览器只使用其中一个字符( \\n )。 So when the model binder converts the input into a string, you actually have a string that uses two characters. 因此,当模型绑定器将输入转换为字符串时,实际上您有一个使用两个字符的字符串。

There are a number of ways to try to address this, with varying levels of "correctness." 有许多方法可以尝试解决这个问题,具有不同程度的“正确性”。 Here are some posts that address the issue: 以下是一些解决此问题的帖子:

It seems to me that the most correct way is to take a two-pronged approach: 在我看来,最正确的方法是采取双管齐下的方法:

  1. Write your length-checking algorithm in a way that ignores the \\r characters, and 以忽略\\r字符的方式编写长度检查算法,并且
  2. Use a model binder that removes \\r characters from strings sent to the server, prior to server-side validation. 在服务器端验证之前,使用模型绑定程序从发送到服务器的字符串中删除\\r字符

However, bear in mind that this might have a few unexpected results. 但是,请记住,这可能会产生一些意想不到的结果。 For example, if users download a file based on the input they've saved, and then open it in a program like Notepad (which only recognizes \\r\\n combos as newlines) they wouldn't see the line breaks. 例如,如果用户根据他们保存的输入下载文件,然后在记事本(它只识别\\r\\n组合作为换行符)这样的程序中打开它们,他们就不会看到换行符。

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

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