The built-in data verification function of Asp.net MVC provides us with a very convenient data verification experience. However, it is troublesome if we access our action through Ajax and return verification error prompts, after repeated experiments, I finally found a solution. I would like to record it as a memo.
ActionCode
Code
1 [Httppost]
2 Public Actionresult createcomment (Comment comment)
3 {
4 If ( ! Modelstate. isvalid)
5 {
6 List < String > Sb = New List < String > ();
7 // Get All Wrong keys
8 List < String > Keys = Modelstate. Keys. tolist ();
9 // Obtain the modelstatedictionary corresponding to each key.
10 Foreach (Var key In Keys)
11 {
12 VaR errors = Modelstate [Key]. errors. tolist ();
13 // Add error description to sb
14 Foreach (VAR Error In Errors)
15 {
16 SB. Add (error. errormessage );
17 }
18 }
19 Return JSON (SB );
20 }
21 Else
22 {
23 Return JSON (commentrepository. insertcomment (comment ));
24 }
25 }
JavaScript code
Code
$ ( " # Commentform " ). Submit ( Function (){
$. Ajax ({
Type: " Post " ,
URL: " /Ajaxresult/createcomment/ " ,
Data: $ ( This ). Serialize (),
Datatype: " JSON " ,
Success: Function (Data ){
If (Data = True ){
Alert ( " Successful " );
Showpage (ArticleID, pagesize, 1 );
}
Else If (Data ! = True && Data ! = False ){
VaR Result = "" ;
For ( VaR I In Data ){
Result = Result + Data [I] + " \ R \ n " ;
}
Alert (result );
}
},
Global: False
});
Return False ;
});
The specifics will not be explained. You can understand them.