【问题标题】:How to Show Validation Failed Message in popup in MVC如何在 MVC 的弹出窗口中显示验证失败消息
【发布时间】:2014-03-13 12:02:14
【问题描述】:

我面临一个问题我想使用 Razor 在 MVC4 中的 Popup 中显示错误消息。我在我的模型和表单提交中使用不同的验证消息,如果失败我想显示相同的验证消息在我的模型中给出。我正在与您分享我的模型、视图和控制器代码。有人可以帮我这样做吗

型号

                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Web;
                using System.ComponentModel;
                using System.ComponentModel.DataAnnotations;
                using System.Configuration;

                namespace Employee_Mgmt_System.Models
                {
                    public class LoginScreen
                    {
                        [Required(ErrorMessage = "EmployeeID Cannot be Blank")]
                        public string EmpID
                        {
                            get;
                            set;
                        }
                        [Required(ErrorMessage = "Password Cannot be kept Blank")]
                        [DataType(DataType.Password)]
                        public string Password
                        {
                            get;
                            set;
                        }

                    }
                }

控制器

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Web;
            using System.Web.Mvc;
            using Employee_Mgmt_System.Models;
            using System.ComponentModel;
            using System.Data;
            using System.Data.SqlClient;
            using System.Configuration;

            namespace Employee_Mgmt_System.Controllers
            {
                public class LoginScreenController : Controller
                {
                    //
                    // GET: /LoginScreen/
                    LoginScreen Ls = new LoginScreen();
                    [HttpPost]
                    public ActionResult Login(LoginScreen LogScreen)
                    {
                        if (ModelState.IsValid)
                        {

                                return RedirectToAction("HomeScreen", "HomeScreen");



                        }
                        return View("LoginScreen");
                    }

                    public ActionResult LoginScreen()
                    {

                        return View("LoginScreen");
                    }

                }
            }

查看

                @model Project.LoginScreen
                @{
                    ViewBag.Title = "LoginScreen";
                }
                <script src="~/Scripts/jquery-1.7.1.js"></script>
                <script src="~/Scripts/jquery.validate.js"></script>


                <h2>LoginScreen</h2>
                <body>
                    @using(Html.BeginForm("login","loginscreen",FormMethod.Post))
                    {
                      @Html.ValidationSummary(true)  
                        <div style="color:red;text-align:center">
                            <fieldset>
                                <legend>Validation Summary</legend>
                                @Html.ValidationMessageFor(m=>m.EmpID)
                                <br />
                                @Html.ValidationMessageFor(m=>m.Password)
                            </fieldset>

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

                        <table border="1" style="background-color:activeborder">
                            <tr>
                                <td>
                                  @Html.LabelFor(@m=>@m.EmpID)
                                </td>
                                <td>
                                  @Html.TextBoxFor(@m=>@m.EmpID)
                                </td>
                            </tr>

                            <tr>
                                <td>
                                    @Html.LabelFor(@m=>@m.Password)
                                </td>
                                <td>
                                    @Html.PasswordFor(@m=>@m.Password)
                                </td> 
                            </tr>


                        </table>
                    <input type="submit" value="login" />
                    </div>
                    }

                </body>

【问题讨论】:

    标签: jquery asp.net-mvc asp.net-mvc-4 razor


    【解决方案1】:

    这是一个非常简单的方法:

    if (ModelState.IsValid)
     {
        return RedirectToAction("HomeScreen", "HomeScreen");
     }
     StringBuilder sb = new StringBuilder();
     sb.Append("You have a bunch of errors:");
    
     foreach (ModelState modelState in ModelState.Values) {
       foreach (ModelError error in modelState.Errors) {
           sb.Append(error + "\n");
        }
      }
     ViewData["Error"] = sb.ToString();
     return View("LoginScreen");
    

    在你看来:

     @if(!String.IsNullOrEmpty(ViewBag["Errors"])){
          @:<script type="text/javascript">alert('@ViewBag["Errors"]')</script>
     }
    

    这是未经测试的,但应该会给你这个想法。

    【讨论】:

    • 同意!您可以像这样进行所有验证:@:
    • @Sunny 确实如此,我只想指出您不希望在 js 警报框中有任何标记,因此您需要注意ValidationSummary。使用\n 而不是&lt;li&gt;
    • @Chris,sunny 我不想要您使用 ViewBag 提供的用户定义错误消息,我想获取我在模型中使用 Required 属性声明的消息。当模型失败并在 mvc 视图中显示时如何获取该错误消息
    • @Rahul 更新了,现在应该更有用了。
    • @Chris Controller 部分我实现得很好,但是当我试图在视图中执行此操作时,我遇到了错误,而且还有一件事在我的视图中编写视图代码......你能更新吗用我的观点..
    【解决方案2】:

    作为替代方案,如果您使用引导程序,请尝试我为类似问题构建的小验证摘要控件/想要一种更好的方法来控制标准验证摘要控件的样式。

    https://github.com/JellyMaster/MVCBootstrap

    这是一个可以在多种模式下工作的验证摘要控件:

    面板、警报、可关闭警报和模式。

    您可以查看项目中的示例图片以了解其外观。

    它可以自定义样式并显示模型错误以及自定义错误。您还可以将自己的 CSS 类包含到控件中以覆盖默认引导样式。

    【讨论】:

      【解决方案3】:

      要实现这种显示机制,您可以

      1. 将查看页面分成两部分,查看页面和部分查看页面。将 HTML.BeginForm 中的 HTML 标记移动到局部视图中。 Ajaxify 局部视图页面。
      2. 在视图页面中定义一个 div 以将消息显示为弹出窗口。定义必要的 jQuery 方法来打开弹出窗口。
      3. 向 HTMLHelper 类添加扩展方法以显示弹出消息。此方法将负责从模型状态及其显示构造错误消息。

      随附的示例代码。请看一下代码。注意:我还没有测试过。

      查看页面(login.cshtml)

      @model Project.LoginScreen
      @{
          ViewBag.Title = "LoginScreen";
      }
      <script src="@Url.Content("~/Scripts/jquery-1.9.1.js")"></script>
      <script src="@Url.Content("~/Scripts/jquery-ui-1.10.2.js")"></script>
      <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
      <script src="@Url.Content("~/Scripts/jquery.growl.js")"></script>
      
          $(document).ready(function () {
              $.ajaxSetup({
                  cache: false
              });
      
              $(document).ajaxError(function (request, status, error) {
                  $.growl.error({ title: "Server Error", message: status.responseText });
              });
      
              // create the loading window and set autoOpen to false
              $("#loadingScreen").dialog({
                  autoOpen: false,    
                  dialogClass: "loadingScreenWindow",
                  closeOnEscape: false,
                  draggable: false,
                  width: 460,
                  minHeight: 100,
                  modal: true,
                  buttons: {},
                  resizable: false,
                  open: function () {
                      $('body').css('overflow', 'hidden');
                  },
                  close: function () {
                     $('body').css('overflow', 'auto');
                  }
              }); // end of dialog
          });
      
          function waitingDialog(waiting) { 
              $("#loadingScreen").html(waiting.message && '' != waiting.message ? waiting.message : 'Please wait...');
              $("#loadingScreen").dialog('option', 'title', waiting.title && '' != waiting.title ? waiting.title : 'Updating');
              $("#loadingScreen").dialog('open');
          }
          function closeWaitingDialog() {
              $("#loadingScreen").dialog('close');
          }
      </script>
      
      <h2>LoginScreen</h2>
      <div id="frmContent">
          @Html.Partial("loginPartial", Model)
      </div>
      <div id="loadingScreen"></div>
      

      部分视图(loginPartial.cshtml)

      @model Project.LoginScreen
      @using (Ajax.BeginForm("login", "loginscreen", new AjaxOptions { OnBegin = "waitingDialog({})", OnComplete = "closeWaitingDialog()", HttpMethod = "POST", UpdateTargetId = "frmContent" }))
      {
          <div style="color: red; text-align: center">
              <fieldset>
                  <legend>Validation Summary</legend>
                  @Html.ValidationMessageFor(m => m.EmpID)
                  <br />
                  @Html.ValidationMessageFor(m => m.Password)
              </fieldset>
          </div>
          <br />
          <br />
          <div>
      
              <table border="1" style="background-color: activeborder">
                  <tr>
                      <td>
                          @Html.LabelFor(@m => @m.EmpID)
                      </td>
                      <td>
                          @Html.TextBoxFor(@m => @m.EmpID)
                      </td>
                  </tr>
      
                  <tr>
                      <td>
                          @Html.LabelFor(@m => @m.Password)
                      </td>
                      <td>
                          @Html.PasswordFor(@m => @m.Password)
                      </td>
                  </tr>
      
      
              </table>
              <input type="submit" value="login" />
          </div>
      }
      @(Html.AjaxPopupWindow(Html.ViewData.ModelState))
      

      显示消息的扩展方法

      using System.Text;
      using System.Web;
      using System.Web.Mvc;
      namespace Web.Helper
      {
          public static class ValidationHelper
          {
              public static MvcHtmlString AjaxPopupWindow(this HtmlHelper html, ModelStateDictionary states)
              {
                  StringBuilder sb = new StringBuilder();
      
                  if (HttpContext.Current.Request.HttpMethod == "POST")
                  {
                      sb.Append("<script type=\"text/javascript\">");
      
                      if (!states.IsValid)
                      {
                          var ul_tag = new TagBuilder("ul");
      
                          foreach (var state in states.Values)
                          {
                              foreach (var e in state.Errors)
                              {
                                  var li_tag = new TagBuilder("li");
                                  li_tag.SetInnerText(e.ErrorMessage);
      
                                  ul_tag.InnerHtml += li_tag.ToString();
                              }
                          }
      
                          sb.AppendFormat("$.growl.error({{ title: \"{0}\", message: \"{1}\" }});", "Save Error", ul_tag);
                      }
                      else
                      {
                          sb.AppendFormat("$.growl.notice({{ title: \"{0}\", message: \"{1}\" }});", "Save Changes", "Update Complete");
                      }
      
                      sb.Append(" </script>");
                  }
      
                  return MvcHtmlString.Create(sb.ToString());
              }
          }
      }
      

      希望这可能会有所帮助。谢谢。

      【讨论】:

        【解决方案4】:

        我不确定您的问题是否仍然需要任何帮助,因为问题已经 4 岁了,但是如果有人偶然发现它,我想针对这种情况提出建议,最好使用 Ajax.BeginForm 而不是 HTML .Beginform,在不重新加载页面的情况下显示验证,这里是这篇教程文章

        https://qawithexperts.com/article/asp.net/validate-pop-up-modal-using-ajaxbeginform-in-c-mvc/52

        如果你是 Ajax.BeginForm 的新手,你也可以阅读

        https://qawithexperts.com/article/asp.net/use-of-ajaxbeginform-in-aspnet-mvc-c/39

        注意:我是这两篇文章的作者,但你应该使用 AJAX.Beginform。

        【讨论】:

          猜你喜欢
          • 2011-01-01
          • 2015-05-14
          • 2014-01-13
          • 1970-01-01
          • 1970-01-01
          • 2014-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多