Get all error messages in controller. modelstate

Source: Internet
Author: User

The MVC entity verification framework is used for Ajax submission and error messages are returned.

Extension Method implementation

 

Public Static Class Modelstateextensions
{
Public Static String Expenderrors ( This System. Web. MVC. Controller)
{
System. Text. stringbuilder sberrors = New System. Text. stringbuilder ();
Foreach ( VaR Item In Controller. modelstate. values)
{
If (Item. errors. Count> 0 )
{
For ( Int I = item. errors. Count- 1 ; I> = 0 ; I --)
{
Sberrors. append (item. errors [I]. errormessage );
Sberrors. append ( " <Br/> " );
}
}
}
Return Sberrors. tostring ();
}
}

// The efficiency of loop traversal is not as good as that of LINQ, and it needs to be optimized.
Public Static String Expenderrors2 ( This Controller)
{
System. Text. stringbuilder sberror = New System. Text. stringbuilder ();
( From Key In Controller. modelstate. Keys
Where Controller. modelstate [Key]. errors. Count> 0
Select Key)
. Aggregate (sberror, (SB, key) =>
{
Return Controller. modelstate [Key]. Errors
. Aggregate (SB, (sbchild, error) => sbchild. appendformat ( " {0} <br/> " , Error. errormessage ));
});
Return Sberror. tostring ();
}

//Call
If(Modelstate. isvalid)
{
//Do something
ReturnContent ("0");
}
Else
{
ReturnContent (This. Expenderrors ());
}

 

Original article: http://www.cnblogs.com/eyu/archive/2011/01/23/1942291.html

 

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.