开发者

asp.net mvc 2 client side validation missing ValidationRules on custom attribute

开发者 https://www.devze.com 2023-01-14 05:02 出处:网络
Can\'t seem 开发者_如何转开发to get checkbox to be validate on client-side using asp.net mvc 2.Here is my code.

Can't seem 开发者_如何转开发to get checkbox to be validate on client-side using asp.net mvc 2. Here is my code.

Model

[Serializable]
public class RegistrationModel
{
    bool termsAndCondition = false;
    [RequiredToBeTrue(ErrorMessage = "Need terms and service")]
    public bool TermsAndConditions
    {
        get
        {
            return termsAndCondition;
        }
        set
        {
            termsAndCondition = value;
        }
    }
}

Custom Attribute

public class RequiredToBeTrueAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        return (value != null) && (value is bool) ? (bool)value : false;
    }
}

View

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<RegistrationModel>" %>

 <% Html.EnableClientValidation(); %>
 <% using (Html.BeginForm("Register", "Registration", new { area="Account", id = "openid_form", inRegistration = true }))
 <%=Html.ValidationSummary(false)  %>
 blah blah blah
 <div class="checkbox"><label><%= Html.CheckBoxFor(model => model.TermsAndConditions) %>I agree to the <a href="content/terms-conditions.html" id="terms-contents">terms and conditions</a> of use.</label></div>
 <input type="submit" id="submit" name="submit" value="Join Now" />
 <%
    Html.ValidateFor(m => m.TermsAndConditions);            
 %>
 <% } %>      

I am trying to call Html.ValidateFor at the end to push up all error message at top of the page. However, the property "TermsAndConditions" is not getting validated on client side (works great on server side). This leads me to look at the the window.mvcClientValidationMetData method at that mvc push out and I saw the following:

{"FieldName":"TermsAndConditions","ReplaceValidationMessageContents":false,"ValidationMessageId":null,"ValidationRules":[]}

Which you can see that "ValidationRules" are empty meaning that it is trying to validate it but the error message wasn't push out to the client for some reason.

Any ideas? Any help is appreciated.


Seems like I need to do more digging first. Was hoping the new attribute will appear magically on the client side. Instead, have to write some customer javascript to wire it up. See phil hack's post for detail.


This article from Phil Haack, ASP.NET MVC 2 Custom Validation, should help point you in the right direction.

Basically you need to create your own DataAnnotationsModelValidator<RequiredToBeTrueAttribute> and then write some client side script to get it done.

HTHs,
Charles

0

精彩评论

暂无评论...
验证码 换一张
取 消