Take the 2-minute tour ×

I can't get xVal validation to work with strongly typed viewmodels.

Every method in xVal seems to want a prefix which is not used when dealing with strongly typed viewmodels.

My view contains code similar to this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ContactForm>" %>
<%= Html.TextBox("firstName", Model.FirstName) %>

And the following code goes in the controller:

	var theModel = form.ToModel();
catch (RulesException ex)
	ex.AddModelStateErrors(ModelState, string.Empty); // Passing string.Empty for prefix, since I don't use prefixes.

return View(form);

However, the above code doesn't work. I've surely missed something, but don't know what. This is my first time using xVal.

Thankful for any help!

share|improve this question
What do you mean by "the above code doesn't work"? Where does the ToModel() function above come from? How does your Model look? I'd need to see much more info to figure out what's wrong here... –  Adrian Grigore Nov 17 '09 at 15:20

3 Answers 3

up vote 0 down vote accepted

I think the problem is in the fact that you don't use prefixes. If you debug the ModelState you can see validations for things like ".FirstName" although they should be like "FirstName". Because of that the client side validation summaries and stuff doesn't show those validation error messages.

I think this is a bug in xVal.

share|improve this answer

Your posting to not nearly concise enough for me to figure out what's going wrong, but you can find a fully working demo website at the end of this blog article. The article also describes everything you need to do step by step, so this should help you get xVal running.

share|improve this answer

To Adrian's point, we can't see if you are using DataAnnotations on your view model, or if you are using any sort of runner described in this article . You'll need to use a something like the DataAnnotationsValidationRunner it mentions to execute validation on each property of your view model as specified by the validation attributes you use (e.g., Required, Range, etc.).

Basically the steps would be:

  1. Retrieve your updated strongly-typed view model from the form.
  2. Pass that model to your DataAnnotationsValidationRunner, collecting any errors that result
  3. If there were any errors (ErrorInfo objects), throw them as a RulesException
  4. Catch the RulesException and add the validation exceptions to your model using the exception's AddModelStateErrors method
  5. Check to see if ModelState.IsValid, and if it isn't, represent your view, which thanks to your exception handling will now have the errors bound to your view model. You'll have to make sure you have the appropriate ValidationMessage html helper calls in place, also referenced by the linked article.
share|improve this answer

Your Answer


