Asp.Net MVC

モデルレベルの検証属性の作成サンプル

モデルクラス

[EndDateValidation]
public class CustomDate
{
    [DisplayFormat(DataFormatString = "0:dd-MM-yyyy}")]
    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }
    [Required]
    public string Test { get; set; }
}

検証属性クラス

[AttributeUsage(AttributeTargets.Property|AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class EndDateValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
      CustomDate date = value as CustomDate;
   
      return date.EndDate > date.StartDate ? true : false;
    }
}

Binderクラス

public class CustomDateBinder : DefaultModelBinder
{
    protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        //base.OnModelUpdated(controllerContext, bindingContext);
        IDataErrorInfo errorProvider = bindingContext.Model as IDataErrorInfo;
        if (errorProvider != null)
        {
            string errorText = errorProvider.Error;
            if (!String.IsNullOrEmpty(errorText))
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorText);
            }
        }

        foreach (ModelValidator validator in bindingContext.ModelMetadata.GetValidators(controllerContext))
        {
            foreach (ModelValidationResult validationResult in validator.Validate(null))
            {
                bindingContext.ModelState.AddModelError(CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName), validationResult.Message);
            }
        }
    }
}

コントローラ

public ActionResult TestValidator()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestValidator([ModelBinder(typeof(CustomDateBinder))]CustomDate date)
{
    return View();
}


セシウム137を97.7%吸着

コメント:



(画像の文字列を入力して下さい)

トップ   編集 凍結 差分 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019/12/02 (月) 12:32:20 (1627d)

G|Cg|C@Amazon Yahoo yV

z[y[W yVoC[UNLIMITȂ1~] COiq COsیI