【发布时间】:2015-08-17 10:47:47
【问题描述】:
我有一个 MVC 应用程序和一个简单的 Product 模型。ProductName 属性是必需的,但是当我单击 Create 按钮而不提供 ProductName 时,我没有收到任何验证错误,并且调用了 Create 的 HttpPost 方法。
1.型号:
public class Product
{
public int ProductID { get; set; }
[Required(ErrorMessage="The product name cannot be blank")]
[Display(Name="Product")]
public string ProductName { get; set; }
[Required(ErrorMessage="Please provide the creation date")]
[DataType(DataType.Date)]
public DateTime CreationDate { get; set; }
}
2.控制器:
public class ProductController : Controller
{
public ActionResult Index()
{
var product1 = new Product
{
ProductID = 0,
ProductName = "Banana",
CreationDate = DateTime.Now
};
var product2 = new Product
{
ProductID = 1,
ProductName = "Apple",
CreationDate = DateTime.Now
};
var products = new List<Product>() { product1,product2};
return View(products);
}
[HttpGet]
public ViewResult Create()
{
return View();
}
[HttpPost]
[ActionName("Create")]
public ActionResult CreateProduct()
{
return null;
}
}
3.查看:
@model MVCProject.Web.UI.Models.Product
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductName)
@Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CreationDate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CreationDate)
@Html.ValidationMessageFor(model => model.CreationDate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
【问题讨论】:
-
是否启用了客户端验证?你也加入了
jquery{version}.js吗? -
当您向 index() 发出新请求时,能否验证控件是否为空?此外,如果页面上包含客户端验证库!
-
运行你的代码,对我来说很好。我想检查一下 Andrei Mikhalevich 的答案
-
您能否将您的评论作为答案发布@StephenMuecke。我必须添加@Scripts.Render("~/bundles/jquery") 现在它可以工作了
标签: c# asp.net-mvc asp.net-mvc-4