当必填字段为空时,MVC ValidationSummary不显示错误

时间:2015-08-17 10:47:47

标签: c# asp.net-mvc asp.net-mvc-4

我有一个MVC应用程序和一个简单的Product模型.AppsName属性是必需的,但是当我单击Create按钮而不提供ProductName时,我没有得到任何验证错误,并且调用了Create的HttpPost方法。< / p>

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.Controller:

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.View:

@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")
}

3 个答案:

答案 0 :(得分:2)

应启用这些设置。请检查您的web.config:

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

你也可以试试这个:

@{ Html.EnableClientValidation(); }

最后一件事:确保浏览器控制台中没有任何客户端错误。

答案 1 :(得分:1)

确保您在视图中添加了jquery{version}.js。例如,如果您使用默认捆绑包,则使用@Scripts.Render("~/bundles/jquery")

旁注,您的属性错误消息不会显示在@Html.ValidationSummary(true)元素中(仅在与每个属性关联的@Html.ValidationMessageFor()元素中),因为您为{{1}指定了true } property。

答案 2 :(得分:0)

检查你的web.config

A

enter image description here