我遇到一个问题,我想使用 Razor 在 MVC4 的弹出窗口中显示错误消息。如果失败,我在模型和表单提交中使用不同的验证消息,我想显示与我相同的验证消息在我的模型中给出。我正在与您分享我的模型、 View 和 Controller 代码。有人可以帮我做到这一点
型号
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");
}
}
}
查看
@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>
最佳答案
这是一个非常简单的方法:
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>
}
这尚未经过测试,但应该可以让您了解。
关于jquery - 如何在 MVC 弹出窗口中显示验证失败消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22378027/