我尝试在我的mvc项目中实现新的validationrules,但我不会在我的视图中成为validationerrormsg。代码有什么问题?我有很多谷歌,我认为我做得很好- -
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))]
有用吗?
我自己解决了这个问题,控制器中的代码是错误的:
[HttpPost]
public ActionResult Create(FormCollection collection)
与一个小的变化:
[HttpPost]
public ActionResult Create(Model1 collection)
效果很好:-)