使用ASP.NET Core提交时,验证消息不会显示

时间:2017-09-20 15:48:21

标签: c# asp.net-core asp.net-core-mvc jquery-validate

我正在开发一个联系页面表单,所以当我提交验证文本时,虽然我按照正确的步骤操作但没有显示3个字段,请参阅下面的图片

enter image description here

这是我的ContactViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace MyApp.ViewModels
{
    public class ContactViewModel
    {
        [Required] 
        public string Name { set; get; }

        [Required]
        [EmailAddress]
        public string Email { set; get; }

        [Required]
        [StringLength(4096, MinimumLength =10)]
        public string Message { set; get; }
    }
}

这是联系人视图

@model MyApp.ViewModels.ContactViewModel
@{
    ViewBag.Title = " Contact Page ";
}


@section scripts {
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}

<h2>Contact me</h2>
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Name"></label>
<input asp-for="Name"/>
<span asp-validation-for="Name" ></span>

<label asp-for="Email" ></label>
<input asp-for="Email" type="email"/>
<span asp-validation-for="Name"></span>

<label asp-for="Message" ></label>
<textarea cols="40" rows="4" asp-for="Message" ></textarea>
<span asp-validation-for="Name"></span>

<div>
    <input type ="submit" value="Send Message"/>
</div>

1 个答案:

答案 0 :(得分:0)

使用ASP.NET MVC帮助程序类

尝试以下操作
@model MyApp.ViewModels.ContactViewModel
@using (Html.BeginForm(new { id = "MyForm" })) 
{
    @Html.LabelFor(m => m.Name)
    @Html.EditorFor(m => m.Name)
    @Html.ValidationMessageFor(m => m.Name)

    @Html.LabelFor(m => m. Email)
    @Html.EditorFor(m => m. Email)
    @Html.ValidationMessageFor(m => m. Email)

    @Html.LabelFor(m => m.Message)
    @Html.EditorFor(m => m.Message)
    @Html.ValidationMessageFor(m => m.Message)

    <br />
    <input type="submit" value="Submit" />
}

您还可以通过将模型中的[required]属性更新为以下示例来添加自定义验证消息:

[Required(ErrorMessage = "Please enter the Name.")]
public string Name { get; set; }