ASP.NET MVC验证消息不显示错误消息

时间:2018-12-01 07:31:35

标签: c# asp.net-mvc razor asp.net-mvc-validation

我看了我的代码和无尽的示例,还看了其他问题,但是我没有尝试对我有用。

我正在尝试验证我的观点。提交时字段边框为红色,但错误消息不可见。

请注意,我使用的是jquery3,问题不是 NoValidate
这是我的控制器的外观:

namespace 2019.Service.Controllers
{
  public class Controller : ApiController
{
    [HttpPost]
    [ResponseType (typeof(PersonResponse))]
    public HttpResponseMessage Post(Person request)
    {
        PersonResponse response = new PersonResponse()
        {
            PersonId = 10000000 + new Random().Next(),
            IsCapped = false,
            Messages = new[] { "Success from WebAPI" },
            IsSuccessful = true,
            IsDuplicate = false
        };

        Console.WriteLine($"Person data received {request.FirstName}");

        return Request.CreateResponse(HttpStatusCode.OK, response);
    }

这是我的观点:

     @{
     Layout = "~/Views/shared/_Layout.cshtml";
     ViewBag.Title = "Page title";
     }
     @using 2019.Host.Models
     @model PersonViewModel
     @using (Html.BeginForm("Submit", "Person", FormMethod.Post, new { id = 
     "frmsubmit" }))
            {
                @Html.ValidationSummary(true);
                @Html.ValidationMessageFor(model => model.FirstName);
                @Html.AntiForgeryToken();
                <div class="col-md-12">
                    <p>
                        <input type="hidden" value="@Model.TrackingCode"  id="hdnTrackingCode" />

                        My name is @Html.TextBoxFor(model => model.FirstName, new { @placeholder = Html.DisplayNameFor(model => model.FirstName) }) }
            @if (Model.Results != null &&
                Model.Results.IsSuccessful)
            {
                <div class="col-md-12 text-center">
                    <img src="~/Content/Images/Products/new-success.png" height="24px" />
                    @Html.ValueFor(model => model.Results.Message)
                </div>
            }

这是我的模型:

using System.Web.Mvc;

namespace 2019.Host.Models
{
public class PersonViewModel
{
    public PersonViewModel()
    {
        Results = new ResultViewModel();
    }

    public string TrackingCode { get; }

    [Required(ErrorMessage = "FirstName is required")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

我的视图中包含以下脚本:

@section Scripts{
<script src='@Url.Content("~/Scripts/jquery-3.3.1.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>
}

这是我的web.config

<appSettings> 
    <add key="webpages:Version" value="3.0.0.0" /> 
    <add key="webpages:Enabled" value="false" /> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
</appSettings>

请参见突出显示的@Html.ValidationSummary(true);生成的代码:

enter image description here

0 个答案:

没有答案