2010-09-01 59 views
0

似乎无法使用asp.net mvc 2在客户端验证复选框。以下是我的代码。asp.net mvc 2客户端验证缺少自定义属性上的验证规则

型号

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

自定义属性

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

查看

<%@ 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);    
%> 
<% } %>  

我想打电话Html.ValidateFor末在顶部推了所有的错误信息页。但是,“TermsAndConditions”属性在客户端没有得到验证(在服务器端很有效)。这使我看的window.mvcClientValidationMetData方法在那个MVC推了,我看到了以下内容:

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

,你可以看到“ValidationRules”是,它是试图验证它毫无意义,但出于某种原因,错误消息没有推送给客户端。

任何想法?任何帮助表示赞赏。

回答

0

好像我需要先做更多的挖掘。希望新的属性会在客户端神奇地出现。相反,必须编写一些客户的javascript来连接它。详情请参阅phil hack的post

0

菲尔哈克的这篇文章,ASP.NET MVC 2 Custom Validation,应该帮助你指出正确的方向。

基本上你需要创建自己的DataAnnotationsModelValidator<RequiredToBeTrueAttribute>然后编写一些客户端脚本来完成它。

HTHs,
Charles