【问题标题】:How to get custom validator to validate client side?如何获取自定义验证器来验证客户端?
【发布时间】:2013-07-11 17:47:11
【问题描述】:

在我的 Mvc 项目中,我有这个模型:

namespace CameraWebApp.Models

    public class Images
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ImageId { get; set; }
        [Required(ErrorMessage="Please enter your first name")]
        public string SubmitterFirstName { get; set; }
        [Required(ErrorMessage = "Please enter your surname name")]
        public string SubmitterLastName { get; set; }
        [ExistingFileName]
        public string NameOfImage { get; set; }
        [StringLength(140, ErrorMessage="Please reduce the length of your description to below 140 characters")]
        [DataType(DataType.MultilineText)]
        public string DescriptionOfImage { get; set; }
        public string ImagePath { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public DateTime DateAdded { get; set; }
    }

如您所见,NameOfImage 属性具有 [ExistingFileName] 属性,这是一个自定义验证器,此验证器的代码如下:

//Overiding isValid to make a custom Validator
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
{
    if (value!=null)
    {
        string fileName = value.ToString();
        if (FileExists(fileName))
        {
            //If the file exists use default error message or the one passed in if there is one
            return new ValidationResult(ExistingImageErrorMessage ?? defaultExistingImage);
        }
        else
        {
            return ValidationResult.Success;
        }  
    }
    else
    {
        //If theres no value passed in then use error message or default if none is passed
        return new ValidationResult(ErrorMessage ?? DefaultErrorMessage);
    }
}

bool FileExists(string fileName)
{
    bool exists = false;
    //A list is passed all the images
    List<Images> images = cameraRepo.getAllImages().ToList();
    //Loops through every image checking if the name already exists
    foreach (var image in images)
    {
        if (image.NameOfImage==fileName)
        {
            exists = true;
            break;
        }
    }
    return exists;
}

前面的每个属性都在下面的代码中验证客户端:

@using (Html.BeginForm())
{
<div id="errorMessages">
@Html.ValidationSummary(false)
</div>
<label>base64 image:</label>
<input id="imageToForm" type="text" name="imgEncoded"/>  
<label>First Name</label>
@Html.EditorFor(model => model.SubmitterFirstName)
<label>Last Name</label>
@Html.EditorFor(model => model.SubmitterLastName)
<label>Name of Image</label>
@Html.EditorFor(model => model.NameOfImage)
<label>Image Description</label>
@Html.EditorFor(model => model.DescriptionOfImage)
<input type=button id="button"value=" Camera button"/>
<input type="submit" value="Click this when your happy with your photo"/>
}
</div>
@Html.ActionLink("gfd!!", "DisplayLatest")
<script src="@Url.Content("~/Scripts/LiveVideoCapture.js")" type="text/javascript"></script>

除了我的自定义验证 [ExisitingFileName] 之外,所有验证都在客户端工作,我不知道为什么?有谁知道为什么会这样? 提前致谢!

【问题讨论】:

    标签: c# asp.net-mvc validation razor


    【解决方案1】:

    由于它是自定义验证,c# mvc 无法生成客户端验证:您必须为此字段实现自己的自定义客户端验证(使用 Javascript)。在其中您可能想使用 AJAX 调用服务器方法来检查文件名是否已经存在。

    您也可以尝试使用远程验证,这似乎更简单: http://msdn.microsoft.com/en-us/library/ff398048(VS.100).aspx

    【讨论】:

      【解决方案2】:

      在客户端验证时,需要实现 IClientValidateable。这需要您编写客户端验证代码 (javascript) 和服务器端验证代码 (C#)

      http://forums.asp.net/t/1850838.aspx/1

      这篇文章也很有帮助
      http://odetocode.com/Blogs/scott/archive/2011/02/22/custom-data-annotation-validator-part-ii-client-code.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 2017-05-03
        • 1970-01-01
        • 2014-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多