1

I have model property:

public int? RegionId { get; set; }

I create dropdownlist in view:

@Html.DropDownListFor(m => m.RegionId, Model.Regions)

In html:

<select data-val="true" data-val-number="The field RegionId must be a number." 
</select>

I need to remove the attribute data-val-number, because in a particular case it not right for me.

I try in Application_Start:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Also note RegionId is nullable.

How I can remove this attribute on server-side code? (not javascript)

4
  • 2
    What do you plan to put in the RegionId property? It is an integer so you aren't going to be able to put a none numeric value into it. Commented Aug 28, 2012 at 9:50
  • I want be able put in the RegionId null value. Commented Aug 28, 2012 at 9:53
  • Are you have Required attribute on RegionId? Commented Aug 28, 2012 at 10:11
  • I need add him, but data-val-number validation works earlier Commented Aug 28, 2012 at 10:12

2 Answers 2

6

In List need add this item:

new SelectListItem {Text =SiteResources.NotSelected, Selected = true, Value = ""} //(not Value=null)

And this item will be valid for data-val-number

Another way In Application_Start:

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());

But apparently disable implicit DataAnnotation validation for all simple types.

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

Comments

0

As said in the comment by AlexC, if your model expect an integer then you'll need to pass a number. You can avoid to get the validation message by removing the ValidationFor helper, but until the type doesn't match then the Model.IsValid will never be true. If you want to bind a null value to a control, you can do it and your Model.Regions will be something like this

"--Please Select--", Value: null
"US", Value:"1",
"Asia", Value:"2"

2 Comments

In Model.Regions i put: new SelectListItem {Text =SiteResources.NotSelected, Selected = true, Value = null}. But when choose this item in page i see "The field RegionId must be a number."
new SelectListItem {Text =SiteResources.NotSelected, Selected = true, Value = ""} is validated! Good!

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.