【问题标题】:Client-Side Validation MVC 5客户端验证 MVC 5
【发布时间】:2014-09-30 14:27:11
【问题描述】:

我对使用 MVC 比较陌生。我正在尝试使用内置数据注释来设置客户端验证。我已经阅读了一些教程,但似乎无法让它工作。当我单击我的表单提交按钮时,它仍然 POSTS 而不是显示错误消息来通知我没有提供描述。下面是我的类代码和我的视图代码:

类代码:

using System.ComponentModel.DataAnnotations;
namespace TicketSystem.Models
{
using System;
using System.Collections.Generic;

public partial class TICKET
{
    public decimal id { get; set; }
    public string empId { get; set; }
    public short severityId { get; set; }
    public short statusId { get; set; }
    public short categoryId { get; set; }

    [Required(ErrorMessage = "Description is required!!")]
    public string description { get; set; }
    public string logOfActions { get; set; }
    public string deviceType { get; set; }
    public string deviceSerNum { get; set; }
    public System.DateTime dateCreated { get; set; }
 }
}

查看代码:

@Html.LabelFor(m => m.description, "Description:")
@Html.EditorFor(m => m.description, new { rows = 5, @class = "txtBoxDescr" })
@Html.ValidationMessageFor(m => m.description)

【问题讨论】:

  • 你能显示更多的视图代码吗?你是如何构建表单的?
  • 两个最常见的检查问题:1.确保您在 web.config 中启用了不显眼的验证 2.确保您的页面引用了以下 javascript 并且顺序正确:jquery、jquery.validate、jquery .validate.unobtrusive
  • 我在 web.config 中启用了这些值,并且脚本在我的 _Layout.cshtml 中按该顺序呈现,但仍然不起作用
  • 页面有 JS 错误吗?一段错误的 JS 代码可能会破坏页面上的所有其他 JS。

标签: asp.net-mvc validation data-annotations


【解决方案1】:

在您的 Controller 中,请务必使用以下代码:

if ModelState.IsValid()
{
  //Do Something here
   return RedirectToAction("Home");
}

return View(myModel);

您可以查看更好的解释here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2015-09-05
    • 2010-09-14
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多