0

我建立了一个人们可以发表评论的网站。它工作正常。但问题是如果缺少输入,它会显示详细的“服务器错误页面”。但对于用户,我想显示验证消息。(例如:- 姓名是必需的)。我该怎么做?

模型

public class Feedback
{
    public int FeedbackID { get; set; }

    [Required(ErrorMessage="Name is required")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Today's date")]
    [DataType(DataType.Date)]        
    public DateTime AddedAt { get; set; }

    [Required (ErrorMessage="Message is required")]
    public string FeedbackMgs { get; set; }
}

public class FeedbackDBContext : DbContext
{
    public DbSet<Feedback> Feedbacks { get; set; }
}

控制器

private FeedbackDBContext FeedbackDB = new FeedbackDBContext();

    //
    // GET: /Feeback/

    public ActionResult Feedback()
    {            
        FeedbackEntries model = new FeedbackEntries();
        model.Entries = FeedbackDB.Feedbacks.ToList();

        return View(model);
    }

    [HttpPost]
    public ActionResult Feedback (FeedbackEntries fd_model)
    {
        FeedbackDB.Feedbacks.Add(fd_model.Entry);
        FeedbackDB.SaveChanges();

        fd_model.Entries = FeedbackDB.Feedbacks.ToList();
        return View(fd_model);
    }
4

1 回答 1

0

看起来你需要:

a) 启用客户端验证 - 请参阅此处了解详细信息/选项http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

b) 在服务器端保存之前检查模型状态是否有效:

[HttpPost] 
    public ActionResult Feedback (FeedbackEntries fd_model) 
    { 
        if (ModelState.IsValid)
        {
           FeedbackDB.Feedbacks.Add(fd_model.Entry); 
           FeedbackDB.SaveChanges(); 

           fd_model.Entries = FeedbackDB.Feedbacks.ToList(); 

        }

        return View(fd_model);
    } 
于 2012-01-03T09:36:43.593 回答