views:

335

answers:

1

I am following this post.

Server side validations work as expected. But the clientside validators are only getting generated for the ID field.

My Linq2Sql Entity Class has two properties ID & CategoryName and below is my Metadata class

[MetadataType(typeof(BookCategoryMetadata))]
public partial class BookCategory{}

public class BookCategoryMetadata
{
    [Required]
    [StringLength(50)]
    public string CategoryName { get; set; }
}

Method to add a category

/// <summary>
/// Adds the category.
/// </summary>
/// <param name="category">The category.</param>
public void AddCategory(BookCategory category)
{
 var errors = DataAnotationsValidationHelper.GetErrors(category);
 if (errors.Any()) {
  throw new RulesException(errors);
 }

 _db.BookCategories.InsertOnSubmit(category);
 _db.SubmitChanges();
}

Create action in the controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "ID")]BookCategory category)
{
 try {
  _repository.AddCategory(category);
 } catch (RulesException ex) {
  ex.AddModelStateErrors(ModelState, "");
 }

 return ModelState.IsValid ? RedirectToAction("Index") : (ActionResult)View();
}

And the view

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Create</h2>

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>

    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="CategoryName">CategoryName:</label>
            <%= Html.TextBox("CategoryName") %>
            <%= Html.ValidationMessage("CategoryName", "*") %>
        </p>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%=Html.ActionLink("Back to List", "Index") %>
</div>
<%= Html.ClientSideValidation<BookCategory>() %>

Now xVal only generates validation rules for the ID field.

<script type="text/javascript">xVal.AttachValidator(null, {"Fields":[{"FieldName":"ID","FieldRules":[{"RuleName":"DataType","RuleParameters":{"Type":"Integer"}}]}]})</script>

The server side validation for CategoryName works perfect. Why xVal is not generating validation rules for the CategoryName? What am I doing wrong?

A: 

Supposedly, xVal 0.8 has buddy classes working. You can read this post here:

[http://xval.codeplex.com/Thread/View.aspx?ThreadId=54300][1]

If that doesn't fix your problem, try pulling down the latest code for xVal and modifying xVal.RuleProviders.PropertyAttributeRuleProviderBase::GetRulesFromTypeCore to be

 protected override RuleSet GetRulesFromTypeCore(Type type)
 {
   var typeDescriptor = metadataProviderFactory(type).GetTypeDescriptor(type);
   var rules = (from prop in typeDescriptor.GetProperties().Cast<PropertyDescriptor>()
                         from rule in GetRulesFromProperty(prop)
                         select new KeyValuePair<string, Rule>(prop.Name, rule));

   var metadataAttrib = type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();
   var buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : type;
   var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast<PropertyDescriptor>();
   var modelClassProperties = TypeDescriptor.GetProperties(type).Cast<PropertyDescriptor>();

   var buddyRules =  from buddyProp in buddyClassProperties
                              join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name
                              from rule in GetRulesFromProperty(buddyProp)
                              select new KeyValuePair<string, Rule>(buddyProp.Name, rule);

   rules = rules.Union(buddyRules);
   return new RuleSet(rules.ToLookup(x => x.Key, x => x.Value));
 }

Also, if this fixes your problem, you might want to contact Steve Sanderson and let him know this bug is still present.

andymeadows
The older post linked in the post that I was reading had the old xVal dll .. downloading the latest xVal binaries fixed the problem .. Thank you
Zuhaib