jQuery 如何在 MVC 的弹出窗口中显示验证失败消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22378027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:55:31  来源:igfitidea点击:

How to Show Validation Failed Message in popup in MVC

jqueryasp.net-mvcasp.net-mvc-4razor

提问by Rahul

I am facing one issue I want to show the error message in Popup in MVC4 using Razor .I am using different Validation Message in my Model and on form Submission if it is failed I want to show the same validation message which I have given in my model . I am sharing my model,View and controller Code with you .Can some one please help me to do this

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

Model

模型

                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;
                        }

                    }
                }

Controller

控制器

            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");
                    }

                }
            }

View

看法

                @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>

回答by Mister Epic

Here's a really simple way to do it:

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

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");

And in your view:

在您看来:

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

This is untested, but should give you the idea.

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

回答by David Shorthose

As an alternative and if you are using bootstrap try my little validation summary control I built for a similar issue/ wanted a better way of controlling the style of the standard validation summary control.

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

https://github.com/JellyMaster/MVCBootstrap

https://github.com/JellyMaster/MVCBootstrap

This was a validation summary control that can work in a number of modes:

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

Panel, alert, closable alert and modal.

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

You can check the sample images within the project to see what it looks like.

您可以检查项目中的示例图像以查看其外观。

It can be customised style wise and show model errors as well as custom errors. You can also include your own CSS classes into the control to override the default bootstrap styles.

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

回答by Sunil

To implement such display mechanism you may

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

  1. Split the view page into two, as view page and partial view page. Move HTML tags inside HTML.BeginForm into the partial view. Ajaxify the partial view page.
  2. Define a div in view page to display the messages as popup. Define necessary jQuery methods to open the popup.
  3. Add an extension method to HTMLHelper class to display the popup message. This method will take care of constructing error message from model state and its display.
  1. 将查看页面拆分为两部分,分别为查看页面和部分查看页面。将 HTML.BeginForm 中的 HTML 标签移到局部视图中。Ajax 化部分视图页面。
  2. 在视图页面中定义一个 div 以将消息显示为弹出窗口。定义必要的 jQuery 方法来打开弹出窗口。
  3. 向 HTMLHelper 类添加扩展方法以显示弹出消息。此方法将负责从模型状态及其显示构造错误消息。

Sample code attached herewith. Please have a look at the code. Note: I have not tested it yet.

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

View Page(login.cshtml)

查看页面(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>

Partial View (loginPartial.cshtml)

部分视图 (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))

Extension method for display the message

显示消息的扩展方法

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());
        }
    }
}

Hope this may help. Thanks.

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

回答by user3559462

I am not sure if you still need any help on your question as question is 4 years old, but if someone stumbles upon it, I would like to advice for situation's like this, it is better to Ajax.BeginForm instead of HTML.Beginform, to show validation's without reloading the page, here is the tutorial article for this

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

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

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

and if you are new to Ajax.BeginForm you can also read

如果您是 Ajax.BeginForm 的新手,您还可以阅读

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

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

Note:I am the author of both the articles, but AJAX.Beginform is what you should use.

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