MVC客户端错误信息未显示

本文关键字:显示 信息 错误 客户端 MVC | 更新日期: 2023-09-27 18:15:43

我想在我的表单上实现客户端验证,但是当我输入错误的数据时,没有显示错误消息。下面是我的模型代码:

模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace LayoutProject.Models
{
    public class Book
    {
        public int BookId { get; set; }
        [Required]
        public String Title { get; set; }
        public String Author { get; set; }
    }
}

My partial view:

@model LayoutProject.Models.Book    
<h4>Books</h4>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <table>
        <tr>
            <td>@Html.LabelFor(d=>d.BookId)</td>
            <td>@Html.TextBoxFor(d=>d.BookId)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(d=>d.Title)</td>
            <td>@Html.TextBoxFor(d=>d.Title)
                @{ Html.ValidateFor(d => d.Title); }
                @Html.ValidationMessageFor(d=>d.Title, "", new { @class = "text-danger" })
            </td>
        </tr>
        <tr>
            <td>@Html.LabelFor(d=>d.Author)</td>
            <td>@Html.TextBoxFor(d=>d.Author)</td>
        </tr>
    </table>

视图:

    @{
    ViewBag.Title = "CreateBooks";
}
<h2>CreateBooks</h2>
<form action="/Home/SaveBooks" method="post">
    @Html.Partial("_CreateBook")
    <input id="createBook" type="submit" value="Submit"/>
</form>

我的控制器:

[HttpPost]
public ActionResult SaveBooks(Book book)
{
    if (ModelState.IsValid)
    {
        //write code to update student 
        return RedirectToAction("Index");
    }
    return View(book);
}

我已经在我的布局中添加了所需的脚本:validate和不显眼的脚本。但是,每当我提交表单时,如果Title字段为空(这是一个必填字段),它就会进入控制器,不会显示任何错误消息。知道是什么导致了这个错误吗?

我需要添加所有这些脚本吗?

  <script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate-vsdoc.js" type="text/javascript"></script>
<script src="@Url.Content("/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

MVC客户端错误信息未显示

当模型无效时,您将在控制器中返回错误的视图。修改return View(book);返回View("the_actual_view", book);

@Html.ValidationMessageFor (d => d。Title, ", new {@class = "text-danger"})

将validationmessage设置为:"。如果您将其更改为:

@Html.ValidationMessageFor(d=>d.Title, null, new { @class = "text-danger" })

应该可以。

编辑1:Keep [Required] in your model.

我没有看到您设置任何验证消息,所以没有消息要显示。这可能是解决你问题的办法。

[Required(ErrorMessage = "Your Error message here")]

在cshtml视图中,为了不覆盖上面的ErrorMessage设置,请执行以下操作:

@Html.ValidationMessageFor(d=>d.Title, null, new { @class = "text-danger" })