2011-05-17 109 views
2

我的模型,看起来像这样:jQuery和ASP.NEt MVC验证:验证防止对服务器

public class Lesson 
{ 
    public int Id { get; set; } 

    [Required(ErrorMessage = "Naam voor de les is verplicht")] 
    [Display(Name="Naam")] 
    public string Name { get; set; } 

    [Required(ErrorMessage = "Tijd is verplicht")] 
    [Display(Name="Tijd")] 
    public string Time { get; set; } 

    //Prijs is default exclusief BTW 
    [Required(ErrorMessage = "Prijs is verplicht")] 
    [Display(Name="Prijs (excl btw)")] 
    public double Price { get; set; } 

    [Display(Name = "Maximum aantal leerlingen")] 
    public int MaxStudents { get; set; } 
} 

而一个创建视图,看起来像这样:

<div> 
    <div> 
     @Html.LabelFor(model => model.Name) 
    </div> 
    <div> 
     @Html.TextBoxFor(model => model.Name, new { @class = "gt-form-text" }) 
     @Html.ValidationMessageFor(model => model.Name) 
    </div> 
    <div> 
     @Html.LabelFor(model => model.Time) 
    </div> 
    <div> 
     @Html.TextBoxFor(model => model.Time, new { @class = "gt-form-text" }) 
     @Html.ValidationMessageFor(model => model.Time) 
    </div> 
    <div> 
     @Html.LabelFor(model => model.Price) 
    </div> 
    <div> 
     @Html.TextBoxFor(model => model.Price, new { @class = "gt-form-text" }) 
     @Html.ValidationMessageFor(model => model.Price) 
    </div> 
    <div> 
     @Html.LabelFor(model => model.MaxStudents) 
    </div> 
    <div> 
     @Html.TextBoxFor(model => model.MaxStudents, 
      new { @class = "gt-form-text" }) 
     @Html.ValidationMessageFor(model => model.MaxStudents) 
    </div> 
</div> 

Application_Start()方法我将DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes设置为false。如果MaxStudents为空,则Modelstate无效(ModelState.IsValid = false)

我的errormessage没有显示,而不是我得到的errormessage是A value is required

如何才能让ModelState.IsValid成为现实?

+1

我只是让MaxStudents是一个可空的int,并且这个工作正常。但我仍然好奇为什么我的ModelState无效 – 2011-05-17 09:46:49

回答

0

有人与我分享这件事,我会通过它以防万一。有时候,这些验证错误被吞并,很难找到。当我遇到类似的问题时,我将这段代码添加到了ActionResult(HttpPost)中,它让我明白了错误的可能性。

  try 
     { 
      db.Entry(myModel).State = EntityState.Modified; 
      db.SaveChanges(); 

     } 
     catch (DbEntityValidationException dbEx) 
     { 
      foreach (var validationErrors in dbEx.EntityValidationErrors) 
      { 
       foreach (var validationError in validationErrors.ValidationErrors) 
       { 
        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); 
       } 
      } 
     }   // }