views:

108

answers:

1

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?

+2  A: 

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 StringLengthattribute 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

Charlino
Thanks, that Gu post is helpful. It's still very disappointing, however, that I have to go to the trouble of not only creating the buddy class but also specifying all the field lengths explicitly. The "Linq-to-SQL classes" generator knew all this info when it examined my database. Why did it not add these attributes to the generated class? Having to repeat this stuff is *not* DRY! (Not your fault, I know).
Gary McGill
Digression: I disagree that MAXLENGTH on the HTML elements is not worth having - it might not help with security, but at least it helps the user not type for 2 pages only to be told later that he's only allowed 10 chars...
Gary McGill
Point taken. Personally I use client side validation for this which takes care of the user finding out later and also helps not duplicating logic. But with JS disabled MAXLENGTH would do that job before they got the server.
Charlino