views:

248

answers:

3

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:

try
{
 var theModel = form.ToModel();
 _contactRepository.Save(theModel);
}
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!

A: 

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.

Adrian Grigore
A: 

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.
Brandon Linton
A: 

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.

Juho Rutila