MVC中,关于往后台提交的方法有:
1、Html.BeginForm():同步
2、Ajax.BeginForm():异步
3、js或jQuery提交后台
本文体验Ajax.BeginForm()方法。
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层自定义验证逻辑和错误信息。
[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); } }
@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>
原文:http://www.cnblogs.com/jxsd/p/4926575.html