How can I set MAXLENGTH on input fields automatically?
I'm using ASP.NET MVC RC2. I have a set of classes that were auto-generated "Linq-to-SQL Classes", where each class models a table in my database. I have some default "edit" views that use the neat-o Html.TextBoxFor
helper extension to render HTML input fields for the columns in a table.
However, I notice that there is no MAXLENGTH
attribute specified in the generated HTML. A quick google shows that you can add explicit attributes using TextBoxFor
etc. but that would mean that I need to hard-code the values (and I need to remember to do it for every input).
This seems pretty poor, considering that everything was automatically generated directly from the DB, so the size of the columns is known. (Although, to be fair, the 开发者_运维问答web-side stuff has to work with any model objects, not just with Linq-to-SQL objects).
Is there any nice way of getting this to do the right thing?
I wouldn't worry about a max length attribute on your html elements, it's a false sense of security.
What I would do is add a StringLength
attribute to the fields you require max length validation on. This will automatically provide you with server side validation of the length and also provide you with client side validation of the length if you so choose.
If you require more information about ASP.NET MVC 2's new use of the Data Annotations validation attributes, have a read of this blog post by Scott Gu.
Also, you may need to use buddy classes for your generated Linq to SQL classes... in which case you can read a blog post I wrote about it.
HTHs,
Charles
When using MVC/jQuery you can simply reapply the data-val-maxlength-max as maxlength in JavaScript/TypeScript:
$container.find('[data-val-maxlength-max]')
.each((index, item) => {
var $this = $(item);
var maxLength = $this.attr('data-val-maxlength-max');
$this.attr('maxlength', maxLength);
});
Charles, I had the same problem and worked out the solution this morning. Here's the blog post with the source code.
精彩评论