2012-11-24 228 views
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的驗證方法來驗證創建屬性。也這是我的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(); 
     } 
    } 

什麼,我必須做什麼? 感謝

+0

您是否嘗試過調試以查看Validate方法是否被調用?你也可以發佈你的控制器這個視圖的操作方法代碼,請。 –

+0

@PaulTaylor我調試。驗證方法執行兩次!在第一次執行它驗證,但在第二它不驗證! –

回答

2

,因爲一旦當您發佈它越來越調用兩次和模型結合劑結合newReview,而一旦當你調用的SaveChanges。

你應該做的,當你張貼檢查,如果ModelState.IsValid =假,如果是的話返回查看(newReview);

除了你DbEntityValidationException應返回查看(newReview);

,最後檢查出的動作過濾器我寫到這裏 - 你不需要有一個嘗試捕捉 - 只需使用屬性上的控制器的方法或註冊它在應用程序啓動等與調用HandleError

MapEntityExceptionsToModelErrorsAttribute完成