【问题标题】:Data annotation not displaying error message数据注释不显示错误消息
【发布时间】:2017-12-13 17:10:56
【问题描述】:

我想在我的应用程序中使用数据注释,问题是当我单击提交按钮并且未填写必填字段时,我没有看到任何错误消息并提交。在控制器中,model.state 工作正常,但我想我应该看到错误消息。

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace ValidationTest.Models
{
    public class User
    {
        [Required(ErrorMessage = "Enter your name.")]
        public string Name { get; set; }

        public string Lastname { get; set; }
    }
}

观点:

@model  ValidationTest.Models.User

@{
    ViewBag.Title = "Index";
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    @using (Html.BeginForm("Record", "Home"))
    {
        @Html.Label("Name:")
        @Html.TextBoxFor(m => m.Name)
        @Html.ValidationMessageFor(m => m.Name)
        <br />
        @Html.Label("Lastname:")
        @Html.TextBoxFor(m => m.Lastname)
        @Html.ValidationMessageFor(m => m.Lastname)
        <input type="submit" value="Record" />
    }
</body>
</html>

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ValidationTest.Models;

namespace ValidationTest.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Record(User usr)
        {
            if (ModelState.IsValid)
            {
                return Content("It Worked!");
            }

            return RedirectToAction("Index");
        }
    }
}

在我拥有的 ASP.NET MVC 项目内的 Scripts 文件夹中:

bootstrap.js

bootstrap.min.js

jquery-3.2.1.intellisense.js

jquery-3.2.1.js

jquery-3.2.1.min.js

jquery-3.2.1.min.map

jquery-3.2.1.slim.js

jquery-3.2.1.slim.min.js

jquery-3.2.1.slim.min.js

modernizr-2.6.2.js

【问题讨论】:

  • 客户端验证所需的 jquery.validate.js 和 jquery.validate.unobtrusive.js

标签: c# asp.net-mvc data-annotations


【解决方案1】:

您必须添加 jquery.validate.min.js 和 jquery.validate.unobtrusive.min.js 的 JavaScript 脚本引用才能进行客户端验证。

【讨论】:

    【解决方案2】:

    移动 return RedirectToAction("Index");在 if (ModelState.IsValid) 条件中。 返回视图();应在 if 条件之外添加。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多