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