【问题标题】:jQuery and ASP.NEt MVC validation: Prevent validation on serverjQuery 和 ASP.NET MVC 验证:防止在服务器上验证
【发布时间】:2011-05-17 09:27:41
【问题描述】:

我的模型看起来像这样:

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 可以为空且不需要,但是,如果MaxStudents 为空,则Modelstate 无效(ModelState.IsValid = false)

我的错误消息没有显示,而是我得到的错误消息是A value is required

我该怎么做才能让ModelState.IsValid 成为真实的?

【问题讨论】:

  • 我刚刚将 MaxStudents 设置为可为空的 int 并且效果很好。但我仍然很好奇为什么我的 ModelState 无效

标签: jquery-validate asp.net-mvc-3


【解决方案1】:

有人与我分享了这个,如果有帮助,我会传递给我。有时这些验证错误会被吞没,很难找到。当我遇到类似问题时,我将此代码添加到我的 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);
                }
            }
        }           // }

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 2011-05-21
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2016-01-13
    相关资源
    最近更新 更多