视图上未显示验证错误消息

Posted

技术标签:

【中文标题】视图上未显示验证错误消息【英文标题】:validations error messages not showing on the view 【发布时间】:2017-10-19 07:57:56 【问题描述】:

我已经在我的 MVC 页面中实现了一个 mvc kendo 窗口控件,并且表单验证似乎确实有效。我可以在控制器中将模型状态设置为 false,但视图似乎没有显示消息。请注意,WorkLogType、WorkLog Subject 和 Details 是必填字段。我已经在视图模型中设置了所需的属性。我还在视图中为各个控件设置了验证标记。有什么问题?

这是我的代码

查看

@using (Ajax.BeginForm("ActivityWorkLog_Create", "Activity", new AjaxOptions

    HttpMethod = "POST",
    OnSuccess = "OnSuccess",
    OnFailure = "OnFailure"
))


<div class="k-popup-edit-form k-window-content k-content" data-role="window">
    <div class="k-edit-form-container">
        @html.HiddenFor(x => x.RequestID, new  data_bind = "value: requestId" )
        @Html.HiddenFor(x => x.ActivityID, new  data_bind = "value: activityId" )
        @Html.HiddenFor(x => x.CountryCode, new  data_bind = "value: countryCode" )

         <div class="form-group">
            <div class="editor-label">
                @Html.LabelFor(model => model.WorkLogAppliesToName)
            </div>
            <div class="editor-field">
                @(Html.Kendo().ComboBoxFor(model => model.WorkLogAppliesToName)
        .Name("WorkLogAppliesToID")
        .Filter("contains")
        .HtmlAttributes(new  style = "width:300px", @readonly = "readonly" )
        .Placeholder("Select...")
        .DataTextField("WorkLogAppliesToName")
        .DataValueField("WorkLogAppliesToID")

        .DataSource(dataSource => dataSource
            .Read(read => read.Action("GetWorkLogAppliesTo", "WorkLog", new  id = 0 ).Type(HttpVerbs.Post)
            )

        )
                )
                @Html.ValidationMessageFor(model => model.WorkLogAppliesToName, "", new  @class = "text-danger" )
            </div>
        </div>

        <div class="form-group">
            <div class="editor-label">
                @Html.LabelFor(model => model.ActivitySLA)
            </div>
            <div class="editor-field">
                @*@Html.EditorFor(model => model.ActivitySLA)*@
                @Html.TextBoxFor(model => model.ActivitySLA, new  id = "ActivityDesc", @readonly = "readonly", Class = "textBoxFor" )

            </div>
        </div>

        <div class="form-group">
            <div class="editor-label">
                @Html.LabelFor(model => model.ActivityID)
            </div>
            <div class="editor-field">
                @(Html.Kendo().ComboBoxFor(model => model.ActivityID)
    .Name("Activity")
    .Filter("contains")
    .HtmlAttributes(new  style = "width:300px", @readonly = "readonly" )
    .Placeholder("Select...")
    .DataTextField("Description")
    .DataValueField("ActivityID")

    .DataSource(dataSource => dataSource
        .Read(read => read.Action("GetActivity", "WorkLog").Data("additionalActivityInfo").Type(HttpVerbs.Post)
        )//.ServerFiltering(true)
    )//.CascadeFrom("ServiceID").Filter("contains")

                )
                @Html.ValidationMessageFor(model => model.ServiceID, "", new  @class = "text-danger" )
            </div>
        </div>

        <div class="form-group">
            <div class="editor-label">
                @Html.LabelFor(model => model.WorkLogType)
            </div>
            <div class="editor-field">
                @(Html.Kendo().ComboBoxFor(model => model.WorkLogType)
    .Name("WorkLogTypeCode")
    .Filter("contains")
    .HtmlAttributes(new  style = "width:300px" )
    .Placeholder("Select...")
    .DataTextField("WorkLogType")
    .DataValueField("WorkLogTypeCode")

    .DataSource(dataSource => dataSource
    .Read(read => read.Action("GetWorkLogType", "WorkLog").Data("additionalWLTInfo").Type(HttpVerbs.Post))
    )

                )
                @Html.ValidationMessageFor(model => model.WorkLogType, "Please select a worklog type", new  @class = "text-danger" )
            </div>
        </div>

        <div class="form-group">
            <div class="editor-label">
                @Html.LabelFor(model => model.WorkLogSubject)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.WorkLogSubject)
                @Html.ValidationMessageFor(model => model.WorkLogSubject, "", new  @class = "text-danger" )
            </div>
        </div>
        <div class="form-group">
            <div class="editor-label">
                @Html.LabelFor(model => model.WorkLogDetails)
            </div>
            <div class="editor-field">
                @Html.TextAreaFor(model => model.WorkLogDetails, new  htmlAttributes = new  @class = "form-control", cols = "50"  )
                @Html.ValidationMessageFor(model => model.WorkLogDetails, "", new  @class = "text-danger" )
            </div>
        </div>

            <div class="worklogStatusButtonAlign">
                <button id="btnWorkLogSave" type="submit" class="k-button k-button-icontext k-primary k-grid-update">Save</button>
                <button id="btnClose" type="button" class="k-button k-button-icontext k-grid-cancel">Cancel</button>

            </div>

            <div id="statusMessage"> </div>

        </div>
</div>

视图模型

 public class ActivityWorkLogViewModel
    
        [ScaffoldColumn(false)]
        [Display(Name = "WorkLogID", ResourceType = typeof(Resources.Resource))]
        public int WorkLogID  get; set; 
        [Required]
        [Display(Name = "WorkLogTypeCode", ResourceType = typeof(Resources.Resource))]
        public string WorkLogTypeCode  get; set; 
        [Display(Name = "WorkLogType", ResourceType = typeof(Resources.Resource))]

        [Required(ErrorMessage = "WorkLogType is required")]
        public string WorkLogType  get; set; 
        [Required]
        [Display(Name = "WorkLogAppliesToID", ResourceType = typeof(Resources.Resource))]
        public int WorkLogAppliesToID  get; set; 
        [Display(Name = "WorkLogAppliesToName", ResourceType = typeof(Resources.Resource))]
        public string WorkLogAppliesToName  get; set; 
        [Required]
        [Display(Name = "RequestID", ResourceType = typeof(Resources.Resource))]
        public int RequestID  get; set; 
        [Display(Name = "ServiceID", ResourceType = typeof(Resources.Resource))]
        public Nullable<int> ServiceID  get; set; 
        [Display(Name = "ActivityID", ResourceType = typeof(Resources.Resource))]
        public Nullable<int> ActivityID  get; set; 
        [Required(ErrorMessage = "Subject is required")]
        [Display(Name = "WorkLogSubject", ResourceType = typeof(Resources.Resource))]
        public string WorkLogSubject  get; set; 
        [Required(ErrorMessage = "Details is required")]
        [Display(Name = "WorkLogDetails", ResourceType = typeof(Resources.Resource))]
        public string WorkLogDetails  get; set; 
        [Display(Name = "EmailTo", ResourceType = typeof(Resources.Resource))]
        public string EmailTo  get; set; 
        [Display(Name = "IsActive", ResourceType = typeof(Resources.Resource))]
        public bool IsActive  get; set; 
        [Display(Name = "CountryCode", ResourceType = typeof(Resources.Resource))]
        public string CountryCode  get; set; 
        [Display(Name = "ActivitySLA", ResourceType = typeof(Resources.Resource))]
        public string ActivitySLA  get; set; 
    

控制器

[HttpPost]
        public ActionResult ActivityWorkLog_Create(ActivityWorkLogViewModel workLogViewModel)
        
            if (!ModelState.IsValid)
            
                return View("EditorTemplates/_WorkLogEdit", Mapper.Map<ActivityWorkLogViewModel>(workLogViewModel));
            
            WorkLogRepository workLogRepository = new WorkLogRepository();
            workLogRepository.CreateWorkLog(Mapper.Map<WorkLog>(workLogViewModel));
            return PartialView("EditorTemplates/_WorkLogEdit", Mapper.Map<ActivityWorkLogViewModel>(workLogViewModel));
        

Bundle.config

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                     "~/Scripts/jquery-version.js",
                     "~/Scripts/jquery-ui-1.12.1.min.js",
                     "~/Scripts/jquery.validate.min.js",
                     "~/Scripts/jquery.validate.unobtrusive.min.js"
                     ));

【问题讨论】:

如何在问题中加载视图?通过 ajax? 是的。使用 ajax 【参考方案1】:

在您的视图中添加这些行:

<script>
    $(document).ready(function() 
        var form = $('form') // Give Id prop to your from
            .removeData("validator")
            .removeData("unobtrusiveValidation");

        $.validator.unobtrusive.parse(form);
    );
<script>

还要确保将 jquery.validate.jsjquery.validate.unobtrusive.js 添加到您的 View cshtml 中,以便验证正常工作。

【讨论】:

嗨尝试了以下@using (Ajax.BeginForm("ActivityWorkLog_Create", "Activity", new AjaxOptions HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnFailure" ,new id = "ActivityWorkLogForm" )) function OnSuccess(response) $("#statusMessage").text("状态更新");警报(“成功”); var form = $("#ActivityWorkLogForm") .removeData("validator") .removeData("unobtrusiveValidation"); $.validator.unobtrusive.parse(form); 我在成功被调用时看不到我的警报。你确定当model.state返回false时调用成功吗 不,我的意思是您如何加载视图而不是视图中的提交功能。您使用控制器操作返回视图? 是的,我使用控制器动作返回视图

以上是关于视图上未显示验证错误消息的主要内容,如果未能解决你的问题,请参考以下文章

CloudKit 错误:在 Mac 上未经过身份验证,但我已登录

为啥 laravel 验证不显示错误

处理验证错误消息以查看 rails 4

两个模型表单一个视图表单验证不显示

Django 在每个视图中显示消息

Spring 视图层如何显示验证消息提示