MVC 客户端错误消息未显示

use*_*810 2 c# validation annotations asp.net-mvc-3

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

模型:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的部分观点:

@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>
Run Code Online (Sandbox Code Playgroud)

看法:

    @{
    ViewBag.Title = "CreateBooks";
}

<h2>CreateBooks</h2>

<form action="/Home/SaveBooks" method="post">
    @Html.Partial("_CreateBook")
    <input id="createBook" type="submit" value="Submit"/>
</form>
Run Code Online (Sandbox Code Playgroud)

我的控制器:

[HttpPost]
public ActionResult SaveBooks(Book book)
{
    if (ModelState.IsValid)
    {

        //write code to update student 

        return RedirectToAction("Index");
    }
    return View(book);
}
Run Code Online (Sandbox Code Playgroud)

我在我的布局中添加了所需的脚本:验证和不显眼的脚本。但是每当我提交表单时,标题字段为空,这是一个必填字段,它进入控制器并且不会显示任何错误消息。知道什么可能导致此错误吗?

我是否也需要添加所有这些脚本:

  <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>
Run Code Online (Sandbox Code Playgroud)

ref*_*esh 7

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