【问题标题】:mvc 3 validation annotation error messages are not displayed next to the fields form字段表单旁边不显示 mvc 3 验证注释错误消息
【发布时间】:2014-08-10 07:56:33
【问题描述】:

我是 mvc 新手,我有一个消息传递类

[Table("employeeTable")]
public class Messsaging : IValidatableObject
{
    public virtual int id { set; get; }
    [Required]
    public virtual String name { set; get; }
    [Required]
    public virtual String country { set; get; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (name.Equals(null))
        {
            yield return new ValidationResult("this field can'not be empty");
        }
    }
}

我有一个创建操作方法

[HttpPost]
    public ActionResult Create(Messsaging form)
    {
        var newmessage = messageContext.messages.Add(form);
        messageContext.SaveChanges();
        return RedirectToAction("Index");
    }

当我提交表单时,我在项目中收到验证错误异常消息,而不是在我的创建表单上显示错误消息!!任何想法都提前谢谢大家。

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    保存前需要检查ModelState,如果无效,返回视图

    [HttpPost]
    public ActionResult Create(Messsaging form)
    {
      if (!ModelState.IsValid)
      {
        return View(form); // returns the view with errors
      }
      // It OK so save
    }
    

    【讨论】:

    • 非常感谢斯蒂芬!现在可以了,我的讲师在操作方法中没有上述 if 条件的情况下编写了代码,但是他使用的是 mvc3 而我使用的是 mvc4 ,您认为这可能是导致问题的原因吗?非常感谢先生
    • AFAIK,与此相关的 MVC 3 和 4 之间没有区别
    【解决方案2】:

    您忘记在 ValidationResult 构造函数中设置字段名称并使用 string.IsNullOrWhiteSpace() 来检查名称属性的值。

    [Table("employeeTable")]
    public class Messsaging : IValidatableObject
    {
        public virtual int id { set; get; }
        [Required]
        public virtual String name { set; get; }
        [Required]
        public virtual String country { set; get; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                yield return new ValidationResult("this field can'not be empty", new[] { "name" });
            }
        }
    }
    

    【讨论】:

    • 嗨彼得,谢谢你的回答,问题是,即使我删除了自定义验证方法并坚持使用内置一次,我也没有显示任何验证消息,而是我抛出一个错误并指向 saveChanges()。创建操作方法中的行
    • 打开 InnerException-s,你会看到错误是什么,但 Stephen 指出你至少应该使用 ModelState 进行错误检查。
    猜你喜欢
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2012-03-29
    • 2012-06-12
    • 2012-02-17
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多