Rahul
Rahul

Reputation: 127

How to Show Validation Failed Message in popup in MVC

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

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>

Upvotes: 5

Views: 26052

Answers (4)

Vikas Lalwani
Vikas Lalwani

Reputation: 1061

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

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

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.

Upvotes: -1

Sunil
Sunil

Reputation: 2905

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.

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

View Page(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)

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

Upvotes: -1

David Shorthose
David Shorthose

Reputation: 4497

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

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.

Upvotes: -1

Mister Epic
Mister Epic

Reputation: 16733

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.

Upvotes: 3

Related Questions