2

I use the EF-CF, and have the following entities:

Countries, Companies

Companies has a property called CountryId with StringLength attribute and the min and max restrictions (min 3 chars, max 3 chars, country id is ISO-Alpha-3). When the user needs to create a Company, I show a html element with all available countries. This is perfect!

However, when the I execute the jquery validator to the form, this checks for 3 selected options and not the length selected option value.

I need the StringLengthAttribute in my Country Model, I cannot remove it.

I hope to "remove" or "hide" the StringLengthAttribute in the call:
@Html.ValidationMessageFor(model => model.CountryId)

Thanks!

2 Answers 2

1

I think I understand your question. A possible solution would be to use a ViewModel to pass to the view as oppose to using the Company entity directly. This would allow you to add or remove data annotations without changing the entity model. Then map the data from the new CompanyViewModel over to the Company entity model to be saved to the database.

For example, the Company entity might look something like this:

public class Company
{
    public int Id { get; set; }
    [StringLength(25)]
    public string Name { get; set; }
    public int EmployeeAmount { get; set; }
    [StringLength(3, MinimumLength = 3)]
    public string CountryId {get; set; }
}

Now in the MVC project a ViewModel can be constructed similar to the Company entity:

public class CompanyViewModel
{
    public int Id { get; set; }
    [StringLength(25, ErrorMessage="Company name needs to be 25 characters or less!")]
    public string Name { get; set; }
    public int EmployeeAmount { get; set; }
    public string CountryId { get; set; }
}

Using a ViewModel means more view presentation orientated annotations can be added without overloading entities with unnecessary mark-up.

I hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chris! Good Idea. I found the next solution. link
0

Ready!

I remove the rule for the html control.

$("#@(Html.HtmlIdNameFor(model => model.CountryId))").rules("remove", "rangelength");

The "rangelength" is the jquery validation rule for the StringLengthAttribute.

Where "Html.HtmlIdNameFor" is a helper to get the "Id" generated by ASP.NET MVC.
Review How to get the HTML id generated by asp.net MVC EditorFor

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.