ASP .NET中的自定义DateTime验证 - MVC

时间:2011-04-23 12:22:00

标签: asp.net-mvc validation datetime asp.net-mvc-3

我尝试在我的MVC项目中实现新的验证规则,但我不会在我的视图中成为验证错误。 代码有什么问题?我有很多googlet,并认为我做得很好 - .-

WebConfig:

<appSettings>
  <add key="ClientValidationEnabled" value="true"/> 
  <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings>

型号:

public class Model1 : IValidatableObject
{
    [Required]
    [DisplayFormat(DataFormatString="{d:0}", ApplyFormatInEditMode=true)]
    public DateTime Wunschtermin { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Wunschtermin < DateTime.Now) yield return new ValidationResult("error1!", new[] { "Wunschtermin" });
        if (Wunschtermin.Date > DateTime.Today.AddYears(2)) yield return new ValidationResult("error2", new[] { "Wunschtermin" });
    }
    ...

查看:

@model TestMvcApplication.Models.Model1

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
    ...
        <div class="editor-field">
            @Html.EditorFor(model => model.Wunschtermin)
            @Html.ValidationMessageFor(model => model.Wunschtermin)
        </div>
    ...

编辑:

也许我可以覆盖RangeAttribute并避免问题:

[Range (DateTime.Now, DateTime.Today.AddYears(2))]

有用?

1 个答案:

答案 0 :(得分:1)

我自己解决了,Controller中的代码错了:

    [HttpPost]
    public ActionResult Create(FormCollection collection)

稍作修改:

    [HttpPost]
    public ActionResult Create(Model1 collection)

效果很好: - )