Error message for ASP. NET MVC2 obtaining modelstate Verification

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.