How to Show Validation Failed Message in popup in MVC

24,317

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.

Share:
24,317
Rahul
Author by

Rahul

Updated on July 09, 2022

Comments

  • Rahul
    Rahul almost 2 years

    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>
    
  • Sunny Sharma
    Sunny Sharma about 10 years
    Agree! you can put all your validation like this: @:<script type="text/javascript">alert('@Html.ValidationSummary(true)'‌​)</script>
  • Mister Epic
    Mister Epic about 10 years
    @Sunny True enough, I would only point out you don't want any markup in a js alert box, so you need to take care with the ValidationSummary. Use \n instead of <li>.
  • Rahul
    Rahul about 10 years
    @Chris,sunny I don't want the userdefined error message which you gave using ViewBag I want to get the message which I have declared in my Model using Required attribute. How to fetch that error message when model is failing and displaying in view in mvc
  • Mister Epic
    Mister Epic about 10 years
    @Rahul Updated, should be more useful now.
  • Rahul
    Rahul about 10 years
    @Chris Controller part I implemented it well but when I am trying to do this in view I am getting error and also one more thing where to write view code in my view...can u please update using my view..
  • Gaurav Arora
    Gaurav Arora almost 8 years
    @MisterEpic- alert('@ViewBag["Errors"]') should be alert('@ViewData["Errors"]')