MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证
2023-09-11 14:16:52 时间
MVC中,关于往后台提交的方法有:
1、Html.BeginForm():同步
2、Ajax.BeginForm():异步
3、js或jQuery提交后台
本文体验Ajax.BeginForm()方法。
View model
using System;
using System.ComponentModel.DataAnnotations;
namespace XHelent.Models
{
public class Registration : IValidatableObject
{
public string RegisrationUniqueId { get; set; }
[Required]
[Display(Name = "姓名")]
public string Name { get; set; }
[Required]
[Display(Name = "年龄")]
public int Age { get; set; }
public System.Collections.Generic.IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Age < 18)
{
yield return new ValidationResult("年龄至少18岁以上", new String[]{"Age"});
}
}
}
}
让model实现了IValidatableObject,在model层自定义验证逻辑和错误信息。
HomeController
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using XHelent.Models;
namespace XHelent.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Registration());
}
[HttpPost]
public PartialViewResult Index(Registration model)
{
if (ModelState.IsValid)
{
RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
byte[] registrationBytes = new byte[16];
csp.GetBytes(registrationBytes);
model.RegisrationUniqueId = Convert.ToBase64String(registrationBytes);
return PartialView("Success", model);
}
else
{
return PartialView("FormContent", model);
}
}
}
}
无论验证成功或失败,都返回强类型部分视图。
Home/Index.cshtml视图
@model XHelent.Models.Registration
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>当前时间:@DateTime.Now.ToShortDateString()</h2>
<div id="formContent">
@{Html.RenderPartial("FormContent");}
</div>
Home/FormContent.cshtml部分视图
@model XHelent.Models.Registration
@{
AjaxOptions options = new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "formContent" //可忽略
};
}
<style type="text/css">
.field-validation-error {
color: red;
}
</style>
@using (Ajax.BeginForm(options))
{
<fieldset>
<legend>登记</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<div>
<input type="submit" value="登记"/>
</div>
</fieldset>
}
Home/Success.cshmtl视图
@model XHelent.Models.Registration
<h2>恭喜,注册成功了!</h2>
<p>注册号为:@Model.RegisrationUniqueId</p>
没有填写效果:
年龄小于18效果:
输入正确效果:
==总结
使用Ajax.BeginForm()虽然可以实现异步提交并验证,但,如果放到后台管理系统的背景下,返回部分视图可能不是很方便。
相关文章
- java代码调试,打印代码方法执行时间(毫秒级)
- Java描述设计模式(03):工厂方法模式
- $.ajax()方法详解 ajax之async属性 【原创】详细案例解剖——浅谈Redis缓存的常用5种方式(String,Hash,List,set,SetSorted )
- MVC之Ajax.BeginForm使用详解之更新列表 mvc验证jquery.unobtrusive-ajax
- Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的使用方法总结
- asp.net webapi [FromBody]string 获取不到ajax post的数据的解决方法
- Bytes to be written to the stream exceed the Content-Length bytes size specified 解决方法
- jQuery ajax() 方法
- MVC二级联动使用$.ajax方法获取后端返回的字符串
- JavaScript-每隔5分钟执行一次ajax请求的实现方法
- 关于sentinel LDK加密war包实现应用加密的使用方法
- $.ajax()方法详解
- struts 页面调用Action的指定方法并传递参数
- js中offsetLeft,offsetTop,offsetParent计算边距方法
- 使用事件CreateEvent注意事项 多进程同步的方法
- MVC4中AJAX Html页面打开调用后台方法实现动态载入数据库中的数据
- Django ajax方法提交表单,及后端接受数据
- Swift - 字典排序方法
- 【ajax】readyState=4并且status=200时,还进error方法
- WebForm.aspx 页面通过 AJAX 访问WebForm.aspx.cs类中的方法,获取数据
- SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder“.的解决方法