验证IValidatableObject的功能不起作用

时间:2012-11-24 06:57:12

标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我有一个“评论”课程:

public class Review : IValidatableObject
{
    public int ReviewId { get; set; }

    [DisplayName("Digning Date")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    public DateTime Created { get; set; }

    [Range(1, 10)]
    public int Rating { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    public string Body { get; set; }
    public int RestaurantId { get; set; }
    public virtual Restaurant Resturant { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var fields = new[]{ "Created"};

        if(Created > DateTime.Now)
        {
            yield return new ValidationResult("Created date cannot be in the future.", fields);
        }

        if (Created < DateTime.Now.AddYears(-1))
        {
            yield return new ValidationResult("Created date cannot be to far in the past.", fields);
        }
    }
}

使用IValidatableObject的Validate方法来验证Create属性。这也是我的cshtml代码:

@model OdeToFood.Models.Review

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@section scripts
 {
<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>
    <legend>Review</legend>

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

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

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

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

验证方法只需检查创建年份是在今年(2012年)或去年(2011年)。因此,如果用户输入2000作为年份,他应该得到错误:“创建日期不能在将来。”。但我不行!

这也是我在web.config中的配置:

<appSettings>
  <add key="webpages:Version" value="1.0.0.0" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

这也是我的控制器代码:

    public ActionResult Create()
    {
        return View(new Review());
    } 

    //
    // POST: /Reviews/Create

    [HttpPost]
    public ActionResult Create(int restaurantId, Review newReview)
    {
        try
        {
            //_db is my DBContext
            var restaurant = _db.Restaurants.Single(r => r.RestaurantId == restaurantId);
            newReview.Created = DateTime.Now;

            restaurant.Reviews.Add(newReview);
            _db.SaveChanges();

            return RedirectToAction("Index");
        }
        catch(System.Data.Entity.Validation.DbEntityValidationException ex)
        {
            return View();
        }
    }

我必须做什么? 感谢

1 个答案:

答案 0 :(得分:2)

它被调用两次,因为一次发布时,模型绑定器绑定到newReview,一次调用SaveChanges。

你应该做的是当你发布检查ModelState.IsValid = false时,如果是,则返回View(newReview);

此外,您的DbEntityValidationException应返回View(newReview);

最后查看我在这里写的动作过滤器 - 您不需要尝试捕获 - 只需在控制器的方法上使用该属性,或者在应用程序启动时注册它就像使用HandleError一样

MapEntityExceptionsToModelErrorsAttribute