How to automatically set maxlengh property for textbox from EF?

195 Views Asked by At

I am using normal helper EditFor to bind data to html controls.

For completeness, here a example:

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @maxlength= 100, @class = "form-control" } })

To set maxlength for string fields, i need to explicitly set the attribute in every view that uses the same table field and there are many views and strings value in the data model.

Doing this in every page is error prone. Changes is size will break the app if a place is forgotten.

How to pass the length directly from EF Model?

2

There are 2 best solutions below

0
DavidG On

The easiest option is to add the [MaxLength(50)] attribute to the model property. For example:

public class SomeModel
{
    [MaxLength(50)]
    public string SomeProperty { get; set; }
}

You can then omit the maxlength property from the call to @Html.EditorFor() and it will be taken from the model metadata.

1
SUNIL DHAPPADHULE On

You can use the Fluent API to configure a maximum length for a property. In this example, targeting SQL Server this would result in the nvarchar(500) data type being used.

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Test>()
                .Property(b => b.Description)
                .HasMaxLength(500);
        }

Or You can use the Data Annotations to configure a maximum length for a property.

public class Test
    {
        [MaxLength(500)]
        public string Description{ get; set; }
    }