简体   繁体   English

asp.net mvc 项目在使用 Ajax.BeginForm 时不显示带有自定义注释的错误消息

[英]asp.net mvc project does not display error message with custom annotation when using Ajax.BeginForm

\\ please am trying to build a project that when a user fill in newsletter form, the form should validate the input especally if the email already exit. \\ 请尝试构建一个项目,当用户填写时事通讯表单时,表单应验证输入,特别是如果电子邮件已经退出。 the problem am having with this is that, when i insert the data with an existing email.与此有关的问题是,当我使用现有电子邮件插入数据时。 the custom annotation does not display the error for the user, and it runs success ajax method, instead of display the error to the user.自定义注解不会向用户显示错误,而是运行成功的ajax方法,而不是向用户显示错误。 When i debug with break points every thing code runs expeceted output especially the error message for custom annotation appear.当我使用断点进行调试时,每件事代码都会运行预期输出,尤其是出现自定义注释的错误消息。 i findout that it works with @Html.BeginForm(), but not with @Ajax.BeginForm()我发现它适用于@Html.BeginForm(),但不适用于@Ajax.BeginForm()

// custom annotation code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using LiveShows.LiveClass;

namespace LiveShows
{
    public class CheckEmailAttribute : ValidationAttribute, IClientValidatable
    {
        public CheckEmailAttribute() :base("{0} Email Already Exit")
        {

        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
        {
            if(value != null)
            {
                var email = value.ToString();

                DetailInfo details = new DetailInfo();
                bool EmailExit = details.CheckEmailIfExist(email);
                if (EmailExit == true)
                {
                  // var ErrorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult("Email exist");
                }
                else
                {
                    return ValidationResult.Success;
                }
            }
            else
            {
                return new ValidationResult("Field Required");
            }

            //base.IsValid(value, validationContext);

    }
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage =
            FormatErrorMessage(metadata.GetDisplayName());

            rule.ValidationType = "checkemail";
            yield return rule;
        }


    }
}
// model code 
   public class EmailFeedsVm
    {
        public int id { get; set; }

        [Required (ErrorMessage ="Your Name is Required")]
        public string DisplayName { get; set; }

        [CheckEmail (ErrorMessage ="Email Already Exist")]
        [Required (ErrorMessage ="Email field is Required")]
        public string Email { get; set; }
        public string DateJoined { get; set; }
    }
// controller code with actiom

[HttpPost]
        public ActionResult NewsLetters(Vmclass.RegisterFeeds fd)
        {
            if (ModelState.IsValid) {
                var feeds = new LiveClass.RegistrationTasks();
                bool RegFeeds = feeds.RegisterEmailFeed(
                    fd.EmailFeeds.DisplayName, fd.EmailFeeds.Email);
                if (RegFeeds == true)
                {
                    return View(fd);
                }
                else
                {
                    return View(fd);
                }
            }
            return View(fd);

        } 
// javascript code 
var EmailMsg = '<h4>Thank You for Joining Us</h4> <p>We will Send You the most Exclusive Events</p>';

function hideLoader(){
    loadingUI.attr("style","none")
}

function Success()
{
    // hideLoader();
    Mymodal.modal('show');
    $("#msgHeading").text("Status");
    $("#status").html('<img src="../img/com/ok.png" />');
    $("#Content").html(EmailMsg);

}
function failure() {
    //    hideLoader();
    Mymodal.modal('show');
    msgHeading.text("Status");
    $("#status").html('<img src="../img/com/Cancel.png" />');
    $("#Content").text("Registration Failed");

}
// view code
   <p id="loading" style="display:none">Loading</p>
            @using (Ajax.BeginForm("NewsLetters", "Home", new AjaxOptions {

                HttpMethod="post",
                OnFailure = "failure",
                OnSuccess = "Success",

               LoadingElementId = "loader",


            }, new { id = "getEmail" }))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary()
                    <div class="form-group">
                        @Html.LabelFor(a => a.EmailFeeds.DisplayName, "Name", new { @class = "form-label" })
                        @Html.TextBoxFor(a => a.EmailFeeds.DisplayName, "Email",new {@class = "form-control" })
                        @Html.ValidationMessageFor(a => a.EmailFeeds.DisplayName)
                    </div>
                    <div class="form-group">
                      @Html.LabelFor(a => a.EmailFeeds.Email, new { @class = "form-label" })
                        @Html.TextBoxFor(a => a.EmailFeeds.Email, new { @class = "form-control" })
                        @Html.ValidationMessageFor(a=>a.EmailFeeds.Email)
                    </div>
                    <button class="btn btn-blue" id="sendEmail" type="submit" >  <img style="display:none" src="../img/ajax-img/smLoader.gif"  id="imgBtn" height="25" /> Done! </button>
            }
            </div>
           <div id="notify">
               <div class="notify">
                   <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal-label">
                       <div class="modal-dialog" role="document">
                           <div class="modal-content">
                               <div class="modal-header">
                                   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                   <h4 class="modal-title" id="myModal-label"> <span id="msgHeading"></span> </h4>
                               </div>
                               <div class="modal-body">

                                   <div id="status">
                                   </div>
                                   <div id="Content">
                                   </div>

                               </div>
                               <div class="modal-footer">
                                   <div id="msgfooter"></div>
                                   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                               </div>
                           </div>
                       </div>
                   </div>
               </div>
       </div>

i also see this error in my watch tab我也在我的手表标签中看到了这个错误

With your current code, Even if the ModelState.IsValid returns false, the action method returns a view result.使用您当前的代码,即使 ModelState.IsValid 返回 false,操作方法也会返回视图结果。 For the ajax call, this is a 200 OK response, hence going to the success handler.对于 ajax 调用,这是一个 200 OK 响应,因此转到成功处理程序。

There is no point in returning a view when it is an ajax form submit.当它是一个 ajax 表单提交时,返回一个视图是没有意义的。 What you can do is, if it is an ajax submit, return a JSON response with all the model validation errors and in your success handler check this JSON and display appropriate error messages to the user.您可以做的是,如果它是 ajax 提交,则返回包含所有模型验证错误的 JSON 响应,并在您的成功处理程序中检查此 JSON 并向用户显示适当的错误消息。

[HttpPost]
public ActionResult NewsLetters(Vmclass.RegisterFeeds fd)
{
   var list = new List<string>();
   if (!ModelState.IsValid)
   {
      var errors = ViewData.ModelState.Values
                         .SelectMany(f => f.Errors
                                          .Select(x => new {Error = x.ErrorMessage,
                                                  Exception =x.Exception})).ToList();
      return Json(new {Status="error",Errors = errors});

   }
  // to do : Your existing code to save
  return Json(new {Status="success"});
}

Now in your success handle check the现在在您的成功句柄中检查

function Success(result) {
    if(result.Status==="error")
    {
      $.each(result.Errors, function(a, b) {
       alert(b.Error);
      });
    }
    else
    {
        $("#status").html("Succesfully saved")
    }
}

Here i am simply alerting each of the errors.在这里,我只是提醒每个错误。 You can update that part to display errors in a list and append that to the DOM.您可以更新该部分以在列表中显示错误并将其附加到 DOM。

If you want the same action method to work with ajax form submission and not ajax submission, you can conditionally return a json response/view result.如果您希望相同的操作方法与 ajax 表单提交而不是 ajax 提交一起使用,您可以有条件地返回一个 json 响应/查看结果。 The Request.IsAjaxRequest() method will come handy here Request.IsAjaxRequest()方法在这里会派上用场

if(Request.IsAjaxRequest())
{
   return Json(new {Status="error",Errors = errors});
}
else
{
   return View(fd);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM