Wednesday 31 March 2010

Asp.Net Dynamic Data – StringLengthAttribute

The name of this attribute says it all – it allows you to specify the maximum length of a string and Its signature is almost the same as the RequiredAttribute
StringLength(“Maximum Length”“Error Message”, “Error Resource”, “Error Resource Type”)
The only issue is that when you set this attribute it sets the text box max length which means that it is impossible for the user to exceed the maximum you set so any error message will never be displayed!

However, this is the same behaviour that Dynamic Data does by default based on the table definition, so the attributes real use is either when you want to restrict the length of a string so that its shorter than the database allows, or if using Entity Framework and you create your own entity you can limit the length of data entered using the standard dynamic data functionality.

As per always to use simply decorate the property with the attribute

[StringLength(15)]
public object City { get; set;}

The user won’t actually see anything they just won’t be able to enter any text longer than the length you’ve set.

No comments:

Post a Comment