0

我有一个“评论”课程:

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>

Validate 方法只是检查创建日期的年份是在今年(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();
        }
    }

我必须做什么?谢谢

4

1 回答 1

2

它被调用了两次,因为一次是在您发布并且模型绑定器绑定到 newReview 时,一次是在您调用 SaveChanges 时。

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

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

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

MapEntityExceptionsToModelErrorsAttribute

于 2012-11-24T08:31:58.517 回答