Original: MVC validation 09-Asynchronous validation using MVC's Ajax.beginform method
In MVC, the methods for submitting to a future table are:
1, Html.BeginForm (): Synchronization
2, Ajax.beginform (): Async
3, JS or jquery submission background
This article experiences the Ajax.beginform () method.
View model
using System;
using System.ComponentModel.DataAnnotations;
namespace Xhelent.models
{
Public class Registration:ivalidatableobject
{
Public string Regisrationuniqueid {get; set;}
[Required]
"name")]
Public string Name {get; set;}
[Required]
"Age")]
Public int Age {get; set;}
Public System.collections.generic.ienumerable<validationresult> Validate (Validationcontext ValidationContext)
{
if (Age < 18)
{
yield return New Validationresult ("At least 18 years old"new string[]{"Age"});
}
}
}
}
The model implements the Ivalidatableobject, customizing the validation logic and error information at the model level.
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)
{
New RNGCryptoServiceProvider ();
byte New byte [16];
Csp. GetBytes (registrationbytes);
Model. Regisrationuniqueid = convert.tobase64string (registrationbytes);
return Partialview ("Success", model);
}
Else
{
return Partialview ("formcontent", model);
}
}
}
}
The strongly typed partial view is returned regardless of validation success or failure.
home/index.cshtml View
@model XHelent.Models.Registration
@{
"Index";
"~/views/shared/_layout.cshtml";
}
<div id="Formcontent">
@{html.renderpartial ("formcontent");}
</div>
home/formcontent.cshtml partial View
@model XHelent.Models.Registration
@{
New Ajaxoptions
{
"Post",
"Formcontent" //Can be ignored
};
}
<style type="Text/css">
. field-validation-error {
color:red;
}
</style>
@using (Ajax.beginform (options))
{
<fieldset>
<legend> Registration </legend>
class="Editor-label">
@Html. labelfor (model = model. Name)
</div>
class="Editor-field">
@Html. editorfor (model = model. Name)
@Html. validationmessagefor (model = model. Name)
</div>
class="Editor-label">
@Html. labelfor (model = model. Age)
</div>
class="Editor-field">
@Html. editorfor (model = model. Age)
@Html. validationmessagefor (model = model. Age)
</div>
<div>
<input type="Submit"value="Registration"/>
</div>
</fieldset>
}
HOME/SUCCESS.CSHMTL View
@model XHelent.Models.Registration
<p> Registration number: @Model .regisrationuniqueid</p>
Did not fill in the effect:Age less than 18 effect:
Enter the correct effect:
= = Summary
While
using Ajax.beginform () can implement asynchronous commits and validate, it may not be convenient to return some of the views if placed in the background of a background management system.