[英]ASP.Net Multiline Textbox Maxlength
I've bee searching for a way to limit the text within a TextBox wich looks like this我一直在寻找一种方法来限制 TextBox 中的文本,看起来像这样
<asp:TextBox runat="server" ID="tbTest" TextMode="MultiLine"
MaxLength="20" Rows="5" Columns="30" >
</asp:TextBox>
The property MaxLength="20"
only works if the other property TextMode="MultiLine"
is not set.属性MaxLength="20"
仅在未设置其他属性TextMode="MultiLine"
时才有效。 It isn't even rendered.它甚至没有被渲染。
The output in the HTML looks like this: HTML 中的输出如下所示:
<textarea name="ctl00$ContentPlaceHolder1$tbTest"
id="ctl00_ContentPlaceHolder1_tbTest" rows="5" cols="30">
</textarea>
If you search here on SO fo a solution to solve this issue, you get 2 ways suggested:如果您在 SO 上搜索解决此问题的解决方案,您会得到 2 种建议:
asp:RegularExpression
) validator and validate the control添加( asp:RegularExpression
)验证器并验证控件BUT但
Most of the answer are prevois 2013 and the support of maxlength
over all browsers was from 2013 as IE10 was released ( reference ).大多数答案是 prevois 2013,所有浏览器对maxlength
的支持是从 2013 年 IE10 发布开始的(参考)。
Currently every Browser supports this attribute - test it on your own: https://jsfiddle.net/wuu5wne1/目前每个浏览器都支持这个属性 - 请自行测试: https : //jsfiddle.net/wuu5wne1/
QUESTION题
How can I force ASP.Net to apply this attribute to my multiline textbox?如何强制 ASP.Net 将此属性应用于我的多行文本框?
Welcome to 2020 - this one finally works now on all Browsers欢迎来到 2020 年 - 现在终于可以在所有浏览器上使用了
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
tbTest.Attributes.Add("maxlength", "20");
}
}
My solution to this was to just manually set the maxlength property via jquery in document.ready:我对此的解决方案是在 document.ready 中通过 jquery 手动设置 maxlength 属性:
$(document).ready(function ()
{
$('#<%=tbTest.ClientID%>').prop('maxlength', 20);
}
Yeah, it's a bit hacky, but if you want to use the asp control (I didn't want to have to deploy a code change), it works.是的,它有点 hacky,但是如果您想使用 asp 控件(我不想部署代码更改),它可以工作。
You could use the below code in your aspx file, 您可以在aspx文件中使用以下代码,
<textarea runat="server" id="tbTest" maxlength="20" rows="5" cols="30" > </textarea>
Hope it helps! 希望能帮助到你!
在 Visual Studio 2019 中,如果添加 columns 属性, maxLength
将起作用
<asp:TextBox runat="server" Columns="1" MaxLength="50" class="form-control" ID="txtFirstName" ClientIDMode="Static" required />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.