Wednesday, February 10, 2010

Not Validating A Complete Model

I am currently trying to edit a single model object through a series of views, using the MVC 2 RC 2 framework, found here:
I discovered that while using the default server-side validation that my model could not be properly validated because some of the model properties were not fully populated, or had incorrect values when, for example, the first view's form was submitted. The incorrect/null/etc values were fine for me because the process had not reached the point they would be populated, but the ModelState.IsValid still returned false, of course. This would be fine, except I needed it to be true, fitting to my standards of what was 'true' about the state of 'my model'.

The method I came up with follows, but I will say that it's not perfect and will almost certainly be superseded by something better in the future. Here it is:

///
/// Used simply to ensure that validation has occured for the model properties that were rendered on
/// the current view.
///
/// The list of form field names to check for errors. Eg: the FormCollection object
/// True if none of the ModelState values matching the whitelist keys have errors attached, else false.
private bool IsModelStateFieldsValidated(IEnumerable whiteList)
{
foreach (string key in whiteList)
if (ModelState[key].Errors.Count > 0)
return false;

return true;
}

If the action method takes a 'FormCollection collection' parameter then that can simply be passed into the IsModelStateFieldsValidated method directly.

The method above just very simply checks the field names which were on the page (which, of course, may not be every property in the model class) and checks that there were no exceptions found in the ModelState value collection - for those property names only. Any other exceptions will be ignored, because they are not pertinent to the current view.

No comments:

Post a Comment