开发者

ASP.NET GridView - how to enable validation declaratively

It it possible to enable validation in an ASP.NET GridView purely declaratively?

What I've tried:

  • A GridView bound to an ObjectDataSource with SelectMethod and UpdateMethod defined

  • The GridView contains some ReadOnly BoundField columns and a TemplateField whose EditTemplate contains a TextBox and a RegularExpressionValidator that only allows numeric input in the TextBox.

  • The GridView also contains a CommandField with ShowEditButton=true and CausesValidation=开发者_开发百科true.

If I click on Edit, enter an invalid value, then click on Save, there is a PostBack, and an exception is thrown in the server (Input string was not in a correct format).

I can of course avoid this by adding validation code to the RowUpdating event handler on the server (see below), but is there any declarative way to force the validation to be done without adding this code?

protected void MyGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Page.Validate("MyValidationGroup");
    if (!Page.IsValid)
    {
        e.Cancel = true;
    }
}


You need that code.

"In addition to relying on client side validation, it is also important that you call Page.IsValid when handling the postback event."

http://weblogs.asp.net/rajbk/archive/2007/03/15/page-isvalid-and-validate.aspx

update

To avoid boiler plate code, you could have all pages inherit from a base class and all user controls inherit from a different base class. The base class will have the common logic (like the one above). You then have to either manually wire it up or walk through the control tree and automatically wire up the events.

I would personally stick with what you currently have though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜