字符串字段长度限制和换行符。

时间:2022-10-05 22:17:55

The scenario I have seems pretty common but I did not found good solution so far. So there's ASP.NET-MVC application with MSSQL database sitting in back-end. The model includes class A with string field Description that needs to be limited to 100 characters. It's declared as follows:

我遇到的情况似乎很常见,但到目前为止我还没有找到好的解决方案。这是ASP。NET-MVC应用程序,使用MSSQL数据库后端。该模型包括了需要限制为100个字符的字符串字段描述的类A。声明如下:

    [StringLength(100)]
    public virtual string Description { get; set; }

The corresponding column in the database is nvarchar with column length = 100. In the UI, Description field is represented by textarea with maxlength = 100.

数据库中相应的列是nvarchar,列长度为100。在UI中,Description字段由maxlength = 100的textarea表示。

Now the issue comes when there're line breaks in the textarea. They are interpreted as 1 character on client side but on server side they are represented by Environment.NewLine which is 2 characters (\r\n). So it exceeds the database column length (actually server side validation fails before the whole back-end thing but let's omit the validation for simplicity).

当textarea中有换行符时,问题就出现了。它们在客户端被解释为1个字符,但在服务器端它们由环境表示。新行是两个字符(\r\n)。因此它超过了数据库列的长度(实际上服务器端验证在整个后端验证之前失败,但是为了简单起见,我们省略验证)。

The solutions I found so far are:

到目前为止,我发现的解决方案是:

  1. Add some magic on client side in order to interpret line break in textarea as two characters. I don't like this solution as it can confuse a user.
  2. 在客户端添加一些技巧,以便将文本区域中的换行符解释为两个字符。我不喜欢这个解决方案,因为它会让用户感到困惑。
  3. Replace \r\n with \n on server side. Seems like a hack that could have some side effects.
  4. 用服务器端上的\n替换\r\n。看起来像是一个可能有副作用的黑客。
  5. Remove/increase column length in the database. The simpliest one (without taking server-side validation issue into account) but let's say it's not the case.
  6. 删除/增加数据库中的列长度。最简单的一种(不考虑服务器端验证问题),但假设不是这样。

I guess there should be something else besides those three.

我想除了这三个以外,应该还有别的东西。

1 个解决方案

#1


1  

This is an old and known issue with MVC (I am not sure if it was solved) but different browsers treat line break differently. My suggestion is to custom model binder like what you find here jQuery validate textarea maxlength bug

这是MVC中一个众所周知的老问题(我不确定它是否已经解决),但是不同的浏览器对待换行的方式不同。我的建议是自定义模型绑定器,就像您在这里找到的jQuery validate textarea maxlength bug一样

#1


1  

This is an old and known issue with MVC (I am not sure if it was solved) but different browsers treat line break differently. My suggestion is to custom model binder like what you find here jQuery validate textarea maxlength bug

这是MVC中一个众所周知的老问题(我不确定它是否已经解决),但是不同的浏览器对待换行的方式不同。我的建议是自定义模型绑定器,就像您在这里找到的jQuery validate textarea maxlength bug一样