Clientside validation attributes on hidden,radio, dropdown elements by default in asp.net mvc 3

孤街浪徒 提交于 2019-12-08 08:48:25

问题


I'm using ASP.NET MVC 3 + FLUENT VALIDATION + NINJECT

I have model X and rules for that model are something like this:

RuleFor(c => c.FirstName).NotEmpty();
RuleFor(c => c.LastName).NotEmpty();

I spotted a little strange thing, the engine puts validation attributes on all hidden elements and on dropdowns, radio buttons, etc.., and I didn't specified this in the validation configuration for that model, so I guess it is by default...

<input type="hidden" value="1" name="Id" id="Id" data-val-required="&amp;#39;Id&amp;#39; must not be empty." data-val-number="The field Id must be a number." data-val="true">

Validation works because hidden element always have a value, but I have a problem with radio buttons. For example, if I don't want one radio button always to be selected by default but empty and if I want to put validation rules on that item, the rendering puts default validation attributes and on top of my rules, so it's getting messed up and validation doesn't work properly...

Anyone had similar issues or knows about this, or do I have to pull the ASP.NET MVC source and look it up by myself? :)

Semi-Lazy and little-pushed-down-by-deadlines coder

Edit:

I tried proposed solution from this link:

Fluent Validations. Error: Validation type names in unobtrusive client validation rules must be unique

but asp.net mvc emits required attributes on each field regardless of AddImplicitRequiredAttribute settings...


回答1:


Make the Id property on your view model a nullable integer.

So instead of:

public int Id { get; set; }

you should use:

public int? Id { get; set; }

Same stands true for any other value types that you don't want to be required. You should use nullable types.

Html helpers automatically emit data-val attributes for all non-nullable types which is by design and if you do not want this behavior you will have to write your own custom HTML helpers to generate your input fields and dropdowns. You can no longer rely on TextBoxFor and DropDownListFor helpers as that's how they are designed.



来源:https://stackoverflow.com/questions/8011615/clientside-validation-attributes-on-hidden-radio-dropdown-elements-by-default-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!