我正在VS2012中制作一个示例MVC4项目..我希望在文本框字段中进行一些验证..但不幸的是它永远不会工作,我发布了我的文件,
我的朋友控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using validators.Models;
namespace validators.Controllers
{
public class FriendController : Controller
{
//
// GET: /Friend/
public ActionResult Create()
{
return View();
}
}
}
我的模特班person.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace validators.Models
{
public class person
{
[Required(ErrorMessage="must")]
[StringLength(10, ErrorMessage="blah")]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
}
}
我正在添加强类型视图....生成以下create.cshtml
@model validators.Models.person
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Firstname)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Firstname)
@Html.ValidationMessageFor(model => model.Firstname)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Lastname)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Lastname)
@Html.ValidationMessageFor(model => model.Lastname)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@*@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}*@
当我运行这个项目并在文本框中输入没有任何值的提交按钮时,没有验证消息....帮助很明显
答案 0 :(得分:2)
将@{ Html.EnableClientValidation(); }
放在您的视图中。如果此helpes则表示在web.config
文件中关闭验证。
同时验证您的脚本是否包含在下一个顺序中:
答案 1 :(得分:1)
Web.config文件
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
在Global.asax文件中
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
确保JS文件是(jquery.validate.js和jquery.validate.unobtrusive.js)