我了解如何创建自定义验证属性。实际上,当我使用种子方法预先填充数据库时,正在执行验证方法,如果失败,则会引发异常。但是,该验证不适用于实体的创建形式。

我是否必须将某些东西更改为HTML(剃须刀形式)?

它只是让我添加验证验证失败的项目。

代码在这里:

namespace Data.Model
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    sealed public class YearsValidationAttribute : ValidationAttribute
    {
        // Internal field to hold the min value.
        readonly int _years;

        public int Years
        {
            get { return _years; }
        }

        public YearsValidationAttribute(int years)
        {
            _years = years;
        }


        public override bool IsValid(object value)
        {
            var years = (int)value;
            bool result = true;
            if (this.Years != null)
            {
                result = Years >= years;
            }
            return result;
        }



        public override string FormatErrorMessage(string name)
        {
            return String.Format(CultureInfo.CurrentCulture,
              ErrorMessageString, name, Years);
        }
    }
}


public class Position
    {
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.Identity)]   
        public int PositionID { get; set; }

        [Required(ErrorMessage = "Position name is required.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "Name should not be longer than 20 characters.")]
        [Display(Name = "Position name")]              
        public string name { get; set; }

        [Required(ErrorMessage = "Number of years is required")] 
        [Display(Name = "Number of years")]
        [YearsValidationAttribute(5, ErrorMessage = "{0} value must be greater than {1} years.")]        
        public int yearsExperienceRequired { get; set; }

        public virtual ICollection<ApplicantPosition> applicantPosition { get; set; }
    }



@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Position</legend>

        @Html.HiddenFor(model => model.PositionID)

        <div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.yearsExperienceRequired)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.yearsExperienceRequired)
            @Html.ValidationMessageFor(model => model.yearsExperienceRequired)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}
有帮助吗?

解决方案

您所拥有的代码不会为您提供客户端验证器,只有服务器端。但这是一个很好的起点。您在服务器上需要执行的操作方法是检查模型是否有效:

public ActionResult YourAction(YourModel model)
{
    if(ModelState.IsValid)
    {
        // Do your save
    }
    else
    {
        // Do your other stuff
    }
}

如果您也需要客户端验证,则可以在此处使用资源: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

您也可以尝试使用 Remote 验证属性: http://msdn.microsoft.com/en-us/library/gg508808(V=VS.98).aspx

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top