ASP.NET MVC 3 unobtrusive validation and radio buttons

给你一囗甜甜゛ 提交于 2019-11-28 07:01:11
Tohid

Please note that the expected behavior of the following code

@Html.RadioButtonFor(x => x.MyEnumProperty, MyEnum.OptionOne)
@Html.RadioButtonFor(x => x.MyEnumProperty, MyEnum.OptionTwo)
@Html.RadioButtonFor(x => x.MyEnumProperty, MyEnum.OptionThree)

is

<input id="MyEnumeration" type="radio" value="Option1" 
       name="MyEnumeration" 
       data-val-required="The MyEnumeration field is required." data-val="true">
<input id="MyEnumeration" type="radio" value="Option2" name="MyEnumeration">
<input id="MyEnumeration" type="radio" value="Option3" name="MyEnumeration">

Why? because Html.SomethingFor(model => model.Property) is meant to generate one html element for one particular property. The way you use it to create more than one element from one property is not correct.

Furthermore, look at the IDs of these 3 radio buttons. They are pretty the same, nah? Is it acceptable to have elements with the same IDs on a html page? Absolutely not! Therefore something needs to be fixed.

Although I thought solving this problem is easier by developing a new Html Extension Methods (reference 2), I tried to solve it in another way (because I'm so stubborn!).

First, We need to change the razor code:

<div>
    @Html.RadioButtonFor(m => m.MyEnumeration, MyEnum.Option1, new { id = "m1" })
    <label for="m1">
        OPTION 1</label>
    @Html.RadioButtonFor(m => m.MyEnumeration, MyEnum.Option2, new { id = "m2" })
    <label for="m2">
        OPTION 2</label>
    @Html.RadioButtonFor(m => m.MyEnumeration, MyEnum.Option3, new { id = "m3" })
    <label for="m3">
        OPTION 3</label>
</div>

Then, a piece of JavaScript/jQuery magic to fix our issue:

<script type="text/javascript">
    $(function () {
        $('[name=MyEnumeration]').each(function (index) { domAttrModified(this); });
    });

    function domAttrModified(obj) {
        //$obj = $(obj);
        $(obj).bind('DOMAttrModified', function () {
            if ($(obj).attr('class').indexOf('input-validation-error') != -1)
                $(obj).parent().addClass('input-validation-error');
            else
                $(obj).parent().removeClass('input-validation-error');
        });
    }
</script>

Anytime the first radio button raises a validation error, this JavaScript code applies error css class (input-validation-error) to the parent element of radio buttons, which is a <div> element.

And anytime validation error goes away (by clicking on any of the radio button elements), error style is removed from the parent element.

It works great in IE and FF, but unfortunately doesn't work in Chrome. The reason is Chrome doesn't support DOMAttrModified event. We can fix it by using this solution: https://stackoverflow.com/a/10466236/538387 , but maybe sometime later.

Again, I believe we need to develop an HTML Extension Method or improve and use an EditorTemplate like this: https://gist.github.com/973482

References:

  1. https://stackoverflow.com/a/7098541/538387
  2. https://stackoverflow.com/a/3448675/538387
  3. https://gist.github.com/973482
  4. Event detect when css property changed using Jquery

This can be performed by using the showErrors callback:

$("form").data("validator").settings.showErrors = function (errorMap, errorList) {
    this.defaultShowErrors();

    $("input[type=radio][data-val=true].input-validation-error").each(function () {
        $("input[name=" + $(this).attr('name') + "]").addClass("input-validation-error");
    });

    $("input[type=radio][data-val=true]:not(.input-validation-error)").each(function () {
        $("input[name=" + $(this).attr('name') + "]").removeClass("input-validation-error");
    });
};

What i did was to disabled the css for the radiobutton and only show the error message. (not sure IE likes this)

.input-validation-error input[type="radio"]
{
    border: 0x solid #ff0000;
    background-color: inherit;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!