我有一个“评论”课程:
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();
}
}
我必须做什么?谢谢