使用Ajax在验证摘要中显示错误消息
目标:
如果您根据输入检索错误,则应在ValidationSummary中显示与Ajax相关的网页,而不刷新网页。使用Ajax在验证摘要中显示错误消息
问题:
我试过了,但效果不好。
我缺少什么部分?
谢谢!
信息:
*我找到了一些网页,但它们并不完全符合我的目的。
*我使用ASP.net MVC
@model WebApplication1.Controllers.PersonnelModel
@{
ViewBag.Title = "Ajax";
}
<h2>Ajax</h2>
<h2>AjaxViewModel</h2>
@using (Html.BeginForm("HtmlViewModel", "Home", null))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>PersonnelModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MailAdress)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MailAdress)
@Html.ValidationMessageFor(model => model.MailAdress)
</div>
</fieldset>
<p>
<input type="submit" value="Html Form Action" />
</p>
}
<br/>
<br />
<h2>AjaxViewModel</h2>
@using (Ajax.BeginForm("AjaxViewModel", "Home", new AjaxOptions { UpdateTargetId = "result" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>PersonnelModel</legend>
<div id="result"></div>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MailAdress)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MailAdress)
@Html.ValidationMessageFor(model => model.MailAdress)
</div>
</fieldset>
<p>
<input type="submit" value="Ajax Form Action" />
</p>
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/jquery.unobtrusive-ajax.min.js"></script>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult HtmlViewModel(PersonnelModel Pmodel)
{
return Content("Hi " + Pmodel.UserName + ", Thanks for the details, a mail will be sent to " + Pmodel.MailAdress + " with all the login details.", "text/html");
}
[HttpPost]
public ActionResult AjaxViewModel(PersonnelModel Pmodel)
{
/*
ModelState.AddModelError("", "login is fail");
return View("Index", Pmodel);
*/
return Content("Hi " + Pmodel.UserName + ", Thanks for the details, a mail will be sent to " + Pmodel.MailAdress + " with all the login details.", "text/html");
}
}
public class PersonnelModel
{
[Required(ErrorMessage = "UserName Required.")]
public string UserName { get; set; }
[Required(ErrorMessage = "Email id Required.")]
public string MailAdress { get; set; }
}
}
编辑 - 2017年3月11日:有一个简单的方法来做到这一点
创建局部视图对于表单,我们将其称为Form.cshtml
,并将表单所需的标记移至该表单。对于您的ajax表单,请将data-ajax-mode
属性值设置为replace
和data-ajax-update
值为同一表单的ID。
如果您正在使用Ajax.BeginForm
helper方法,这是你会怎么做
@model PersonnelModel
@using (Ajax.BeginForm("Create", "Home",
new AjaxOptions { UpdateTargetId = "myform",
InsertionMode = InsertionMode.Replace },new { id="myform"}))
{
@Html.ValidationSummary("", true)
@Html.TextBoxFor(f => f.UserName)
@Html.ValidationMessageFor(model => model.UserName)
@Html.TextBoxFor(f => f.MailAdress)
@Html.ValidationMessageFor(model => model.MailAdress)
<input type="Submit" id="submit" value="Submit" class="btn btn-default" />
}
现在,在你的主视图,简单的调用这个局部视图
@model PersonnelModel
<h2>My form below</h2>
@Html.Partial("Form",Model)
现在的操作方法,当模型状态验证失败,返回部分视图。
public ActionResult Create(PersonnelModel model)
{
if (ModelState.IsValid)
{
// to do : Save
}
if (Request.IsAjaxRequest())
{
return PartialView("Form",model);
}
return View(model);
}
现在,当您提交表单和模型状态验证失败,action方法的代码将返回验证错误消息(通过验证辅助生成)的局部视图结果和jquery.unobtrusive-ajax.js
库代码将取代(因为我们用data-ajax-mode="replace"
)指定了jquery选择器#data-ajax-update
(表单标签及其内部内容)的结果内容以及从服务器返回的响应。
这应该做到这一点。少的客户端代码,相对于我的老的方法(下文)
当剃刀视图被执行的Html.ValidationSummary
方法将被执行。如果您正在执行常规表单(非ajax),则当模型验证失败时(假设您编写类似的代码)并且执行了剃须刀视图代码并且ValidationSummary方法将读取验证错误,您的操作方法通常返回到相同视图从模型状态字典中提取出错信息。
当您使用Ajax.BeginForm
helper方法助手将生成表格上一些额外的数据属性,只要你已经包含了jquery.unobtrusive-ajax.min.js
脚本文件,表单提交会被劫持,它会做一个ajax表单提交代替。
当您执行ajax表单提交时,如果要呈现模型验证消息,则需要显式读取模型验证错误,并将其作为客户端代码可以在UI中读取并显示的JSON响应返回。
[HttpPost]
public ActionResult Index(PersonnelModel model)
{
if (ModelState.IsValid)
{
return Json(new {status = "success", message= "Thanks for the details"});
}
else
{
var errors = new List<string>();
foreach (var modelStateVal in ViewData.ModelState.Values)
{
errors.AddRange(modelStateVal.Errors.Select(error => error.ErrorMessage));
}
return Json(new {status = "validationerror", errors = errors});
}
}
在你看来
现在,确保你有你的AJAX成功处理程序开始表格处理响应JSON
@using (Ajax.BeginForm("Index", "Home", new AjaxOptions { OnSuccess = "OnSuccess", }))
{
@Html.ValidationSummary("", true)
@Html.TextBoxFor(model => model.MailAdress)
<!--Your other form input elements-->
<input type="submit" value="Html Form Action" />
}
注意我用了@Html.ValidationSummary
法2个重载和传递一个空字符串作为第一个参数。这将始终在具有类validation-summary-valid
的div内呈现ul元素。
现在创建您的OnSuccess功能并检查响应并查看响应是否具有状态属性,并且其值为validationerror
。如果是,则循环访问错误集合并添加一个新的li元素和错误。
function OnSuccess(response) {
var $summaryUl = $(".validation-summary-valid").find("ul");
$summaryUl.empty();
if (response.status === 'validationerror') {
$.each(response.errors,
function(a, b) {
$summaryUl.append($("<li>").text(b));
});
} else {
alert(response.message);
}
}
谢谢你的帮助! –
我提出了一个更简单的方法做到这一点的答案。看看 – Shyju