By default if a user now uses our GridView UI
to enter a non-valid UnitsOnOrder/Discontinued combination, our LINQ to SQL
data model classes will raise an exception. The
<asp:LinqDataSource> will in turn catch this error and provides an event
that users can use to handle it. If no one handles the event then the
GridView (or other) control bound to the <asp:LinqDataSource> will catch
the error and provide an event for users to handle it. If no one handles
the error there then it will be passed up to the Page to handle, and if not
there to the global Application_Error() event handler in the Global.asax
file. Developers can choose any place along this path to insert
appropriate error handling logic to provide the right end-user experience.
For the application we defined
above, probably the best place to handle any update errors is by handling
the RowUpdated event on our GridView. This event will get fired
every time an update is attempted on our datasource, and we can access the
exception error details if the update event fails. We can add the below
code to check if an error occurs, and if so display an appropriate error
message to the end-user:
Figure 30
Notice above how we have not added any
validation specific logic into our UI. Instead, I am retrieving the
validation error message string we raised in our business logic and
am using it to display an appropriate message to the end-user (I am then
displaying a more generic error message in the event of other failures).
Notice how I'm also indicating above that I
want the GridView to stay in Edit mode when an error occurs - that way the user
can avoid losing their changes, and can modify the values they entered and
click "update" again to try and save them. We can then add a
<asp:literal> control with the "ErrorMessage" ID anywhere
we want on our page to control where where we want the error message to be
displayed:
Figure 31
And now when we try and update the Product with an invalid
value combination we'll see an error message indicating how to fix it:
Figure 32
The nice thing about using this approach is
that I can now add or change my data model's business rules and not have
to modify any of my UI tier's code to have them pick up and honor the
changes. The validation rules, and corresponding error messages, can be
written and centralized in one place in my data model and automatically applied
everywhere.