Search Results

Search found 200 results on 8 pages for 'dataannotations'.

Page 4/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • Validation Summary for Lists using Data Annotations with MVC

    - by David Liddle
    I currently use a custom method to display validation error messages for lists but would like to replace this system for using with Data Annotations. In summary on validation of my form, I want to display "*" next to each input that is incorrect and also provide a Validation Summary at the bottom that relates each error message to the particular item in the list. e.g. say if validation failed on the 2nd list item on a Name input box and the 4th item on an Address input box the validation summary would display [2] Name is invalid [4] Address is invalid Please ignore if there are mistakes in the code below. I'm just writing this as an example. The code below shows how I was able to do it using my custom version of adding model errors but was wondering how to do this using Data Annotations? //Domain Object public class MyObject { public int ID { get; set; } public string Name { get; set; } public string Address { get; set; } public bool IsValid { get { return (GetRuleViolations().Count() == 0); } } public void IEnumerable<RuleViolation> GetRuleViolations() { if (String.IsNullOrEmpty(Name)) yield return new RuleViolation(ID, "Name", "Name is invalid"); if (String.IsNullOrEmpty(Address)) yield return new RuleViolation(ID, "Address", "Address is invalid"); yield break; } } //Rule Violation public class RuleViolation { public int ID { get; private set; } public string PropertyName { get; private set; } public string ErrorMessage { get; private set; } } //View <% for (int i = 0; i < 5; i++) { %> <p> <%= Html.Hidden("myObjects[" + i + "].ID", i) %> Name: <%= Html.TextBox("myObjects[" + i + "].Name") %> <br /> <%= Html.ValidationMessage("myObjects[" + i + "].Name", "*")<br /> Address: <%= Html.TextBox("myObjects[" + i + "].Address") %> <%= Html.ValidationMessage("myObjects[" + i + "].Address", "*")<br /> </p> <% } %> <p><%= Html.ValidationSummary() %> //Controller public ActionResult MyAction(IList<MyObject> myObjects) { foreach (MyObject o in myObjects) { if (!o.IsValid) ModelState.AddModelErrors(o.GetRuleViolations(), o.GetType().Name); } if (!Model.IsValid) { return View(); } } public static class ModelStateExtensions { public static void AddModelError(this ModelStateDictionary modelState, RuleViolation issue, string name) { string key = String.Format("{0}[{1}].{2}", name, issue.ID, issue.PropertyName); string error = String.Format("[{0}] {1}", (issue.ID + 1), issue.ErrorMessage); //above line determines the [ID] ErrorMessage to be //displayed in the Validation Summary modelState.AddModelError(key, error); }

    Read the article

  • MVC2 Client validation with Annotations in View with RenderAction

    - by Olle
    I'm having problem with client side validation on a View that renders a dropdownlist with help of a Html.RenderAction. I have two controllers. SpecieController and CatchController and I've created ViewModels for my views. I want to keep it as DRY as possible and I will most probably need a DropDownList for all Specie elsewhere in the near future. When I create a Catch i need to set a relationship to one specie, I do this with an id that I get from the DropDownList of Species. ViewModels.Catch.Create [Required] public int Length { get; set; } [Required] public int Weight { get; set; } [Required] [Range(1, int.MaxValue)] public int SpecieId { get; set; } ViewModels.Specie.List public DropDownList(IEnumerable<SelectListItem> species) { this.Species = species; } public IEnumerable<SelectListItem> Species { get; private set; } My View for the Catch.Create action uses the ViewModels.Catch.Create as a model. But it feels that I'm missing something in the implemetation. What I want in my head is to connect the selected value in the DropDownList that comes from the RenderAction to my SpecieId. View.Catch.Create <div class="editor-label"> <%: Html.LabelFor(model => model.SpecieId) %> </div> <div class="editor-field"> <%-- Before DRY refactoring, works like I want but not DRY <%: Html.DropDownListFor(model => model.SpecieId, Model.Species) %> --%> <% Html.RenderAction("DropDownList", "Specie"); %> <%: Html.ValidationMessageFor(model => model.SpecieId) %> </div> CatchController.Create [HttpPost] public ActionResult Create(ViewModels.CatchModels.Create myCatch) { if (ModelState.IsValid) { // Can we make this StronglyTyped? int specieId = int.Parse(Request["Species"]); // Save to db Catch newCatch = new Catch(); newCatch.Length = myCatch.Length; newCatch.Weight = myCatch.Weight; newCatch.Specie = SpecieService.GetById(specieId); newCatch.User = UserService.GetUserByUsername(User.Identity.Name); CatchService.Save(newCatch); } This scenario works but not as smooth as i want. ClientSide validation does not work for SpecieId (after i refactored), I see why but don't know how I can ix it. Can I "glue" the DropDownList SelectedValue into myCatch so I don't need to get the value from Request["Species"] Thanks in advance for taking your time on this.

    Read the article

  • Custom DataAnnotation attribute with datastore access in ASP.NET MVC 2

    - by mare
    I have my application designed with Repository pattern implemented and my code prepared for optional dependency injection in future, if we need to support another datastore. I want to create a custom validation attribute for my content objects. This attribute should perform some kind of datastore lookup. For instance, I need my content to have unique slugs. To check if a Slug already exist, I want to use custom DataAnnotation attribute in my Base content object (instead of manually checking if a slug exists each time in my controller's Insert actions). Attribute logic would do the validation. So far I have come up with this: public class UniqueSlugAttribute : ValidationAttribute { private readonly IContentRepository _repository; public UniqueSlugAttribute(ContentType contentType) { _repository = new XmlContentRepository(contentType); } public override bool IsValid(object value) { if (string.IsNullOrWhiteSpace(value.ToString())) { return false; } string slug = value.ToString(); if(_repository.IsUniqueSlug(slug)) return true; return false; } } part of my Base content class: ... [DataMember] public ContentType ContentType1 { get; set; } [DataMember] [Required(ErrorMessageResourceType = typeof (Localize), ErrorMessageResourceName = "Validation_SlugIsBlank")] [UniqueSlug(ContentType1)] public string Slug { get { return _slug; } set { if (!string.IsNullOrEmpty(value)) _slug = Utility.RemoveIllegalCharacters(value); } } ... There's an error in line [UniqueSlug(ContentType1)] saying: "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type." Let me explain that I need to provide the ContentType1 parameter to the Constructor of UniqueSlug class because I use it in my data provider. It is actually the same error that appears if you try do to this on the built-in Required attribute: [Required(ErrorMessageResourceType = typeof (Localize), ErrorMessageResourceName = Resources.Localize.SlugRequired] It does not allow us to set it to dynamic content. In the first case ContentType1 gets known at runtime, in the second case the Resources.Localize.SlugRequired also gets known at runtime (because the Culture settings are assigned at runtime). This is really annoying and makes so many things and implementation scenarios impossible. So, my first question is, how to get rid of this error? The second question I have, is whether you think that I should redesign my validation code in any way?

    Read the article

  • asp.net MVC 1.0 and 2.0 currency model binding

    - by David Liddle
    I would like to create model binding functionality so a user can enter ',' '.' etc for currency values which bind to a double value of my ViewModel. I was able to do this in MVC 1.0 by creating a custom model binder, however since upgrading to MVC 2.0 this functionality no longer works. Does anyone have any ideas or better solutions for performing this functionality? A better solution would be to use some data annotation or custom attribute. public class MyViewModel { public double MyCurrencyValue { get; set; } } A preferred solution would be something like this... public class MyViewModel { [CurrencyAttribute] public double MyCurrencyValue { get; set; } } Below is my solution for model binding in MVC 1.0. public class MyCustomModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { object result = null; ValueProviderResult valueResult; bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out valueResult); bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult); if (bindingContext.ModelType == typeof(double)) { string modelName = bindingContext.ModelName; string attemptedValue = bindingContext.ValueProvider[modelName].AttemptedValue; string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator; string alternateSeperator = (wantedSeperator == "," ? "." : ","); try { result = double.Parse(attemptedValue, NumberStyles.Any); } catch (FormatException e) { bindingContext.ModelState.AddModelError(modelName, e); } } else { result = base.BindModel(controllerContext, bindingContext); } return result; } }

    Read the article

  • Validate MVC 2 form using Data annotations and Linq-to-SQL, before the model binder kicks in (with D

    - by Stefanvds
    I'm using linq to SQL and MVC2 with data annotations and I'm having some problems on validation of some types. For example: [DisplayName("Geplande sessies")] [PositiefGeheelGetal(ErrorMessage = "Ongeldige ingave. Positief geheel getal verwacht")] public string Proj_GeplandeSessies { get; set; } This is an integer, and I'm validating to get a positive number from the form. public class PositiefGeheelGetalAttribute : RegularExpressionAttribute { public PositiefGeheelGetalAttribute() : base(@"\d{1,7}") { } } Now the problem is that when I write text in the input, I don't get to see THIS error, but I get the errormessage from the modelbinder saying "The value 'Tomorrow' is not valid for Geplande sessies." The code in the controller: [HttpPost] public ActionResult Create(Projecten p) { if (ModelState.IsValid) { _db.Projectens.InsertOnSubmit(p); _db.SubmitChanges(); return RedirectToAction("Index"); } else { SelectList s = new SelectList(_db.Verbonds, "Verb_ID", "Verb_Naam"); ViewData["Verbonden"] = s; } return View(); } What I want is being able to run the Data Annotations before the Model binder, but that sounds pretty much impossible. What I really want is that my self-written error messages show up on the screen. I have the same problem with a DateTime, which i want the users to write in the specific form 'dd/MM/yyyy' and i have a regex for that. but again, by the time the data-annotations do their job, all i get is a DateTime Object, and not the original string. So if the input is not a date, the regex does not even run, cos the data annotations just get a null, cos the model binder couldn't make it to a DateTime. Does anyone have an idea how to make this work?

    Read the article

  • help me with asp.net mvc 2 custom validation attribute

    - by Omu
    I'm trying to write a validation attribute that is going to check that at least one of the specified properties is true [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class AtLeastOneTrueAttribute : ValidationAttribute { private const string DefaultErrorMessage = "select at least one"; public AtLeastOneTrueAttribute(params string[] props) : base(DefaultErrorMessage) { this.props = props; } private readonly string[] props; public override string FormatErrorMessage(string name) { return DefaultErrorMessage; } public override bool IsValid(object value) { var properties = TypeDescriptor.GetProperties(value); return props.Any(p => (bool) properties.Find(p, true).GetValue(value)); } } now when I'm trying to use I can't really get specify the props after the fir , the intellisence shows me that I'm entering the ErrorMessage and only the first string is the params string[] props

    Read the article

  • dataannotation metadatatype register dll in global.aspx (linq to sql)

    - by mazhar
    I am trying to use dataannotation validation(I am not able to Fire the annotations as yet) in my mvc application. with reference to this article I want to confirm http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs I am using vs 2008 professional edition . Do I really need to download Microsoft.web.mvc.dataannotation dll (The other dll is already present in the vs). to use(fire) datannotation on the page.? I am using partial views as well on the pages with dataviewmodel class(I will be using formviewmodel class for validation?)

    Read the article

  • Best Practices - Data Annotations vs OnChanging in Entity Framework 4

    - by jptacek
    I was wondering what the general recommendation is for Entity Framework in terms of data validation. I am relatively new to EF, but it appears there are two main approaches to data validation. The first is to create a partial class for the model, and then perform data validations and update a rule violation collection of some sort. This is outlined at http://msdn.microsoft.com/en-us/library/cc716747.aspx The other is to use data annotations and then have the annotations perform data validation. Scott Guthrie explains this on his blog at http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx. I was wondering what the benefits are of one over the other. It seems the data annotations would be the preferred mechanism, especially as you move to RIA Services, but I want to ensure I am not missing something. Of course, nothing precludes using both of them together. Thanks John

    Read the article

  • Validating a class using DataAnotations

    - by runxc1 Bret Ferrier
    I have a class that I am using to model my data in MVC. I have added some DataAnotations to mark fields that are required and I am using regular expressions to check valid Email Addresses. Everything works fine if the object is posted back to MVC and I have the ModelState property that I can check to confirm that the class is valid but how do I check to see if the class is valid outside of MVC using the same class and Data Anotations that I have already set up?

    Read the article

  • Custom ValidationAttribute test against whole model

    - by griegs
    I know this is probably not possible but let's say I have a model with two properties. I write a ValidationAttribute for one of the properties. Can that VA look at the other property and make a decision? So; public class QuickQuote { public String state { get; set; } [MyRequiredValidator(ErrorMessage = "Error msg")] public String familyType { get; set; } So in the above example, can the validator test to see what's in the "state" property and take that into consideration when validating "familyType"? I know I can probably save the object to the session but would like to avoid any saving of state if possible.

    Read the article

  • ASP.NET MVC DisplayAttribute and interfaces

    - by msi
    I have some interface and classes public inteface IRole { int Id { get; } string Name { get; set; } } public class Role : IRole { public int Id { get; } [Display("Role Name")] public string Name { get; set; } } public class Member { [Display("Login")] public string Login { get; set; } [Display("Password")] public string Password { get; set; } public IRole Role { get; set; } } on View I try to use, View is strongly type of Member on this line displays correct message from DisplayAttribute <%= Html.LabelFor(m => m.Login) %> on this line it does not display correct label from DisplayAttribute <%= Html.LabelFor(m => m.Role.Name) %> How can I fix this to have correct labels in such architecture? Thanks P.S. I know about adding DisplayAttribute to the interface field and all will work, but maybe there are different solution.

    Read the article

  • C# ASPNET MVC - How do you use ModelState.IsValid in a jquery/ajax postback?

    - by JK
    From what I've seen ModelState.IsValid is only calculated by the MVC frame work on a full postback, is that true? I have a jquery postback like so: var url = "/path/to/controller/myaction"; var id = $("#Id").val(); var somedata = $("#somedata").val(); // repeated for every textbox $.post(url, { id: id, somedata: somedata }, function (data) { // etc }); And the controller action looks like: public JsonResult MyAction(MyModel modelInstance) { if (ModelState.IsValid) { // ... ModelState.IsValid is always true, even when there is invalid data } } But this does not seem to trigger ModelState.IsValid. For example if somedata is 5 characters long, but the DataAnnotation says [StringLength(3)] - in this case ModelStae.IsValid is still true, because it hasn't been triggered. Is there something special I need to do when making a jquery/ajax post instead of a full post? Thanks!

    Read the article

  • Custom model validation of dependent properties using Data Annotations

    - by Darin Dimitrov
    Since now I've used the excellent FluentValidation library to validate my model classes. In web applications I use it in conjunction with the jquery.validate plugin to perform client side validation as well. One drawback is that much of the validation logic is repeated on the client side and is no longer centralized at a single place. For this reason I'm looking for an alternative. There are many examples out there showing the usage of data annotations to perform model validation. It looks very promising. One thing I couldn't find out is how to validate a property that depends on another property value. Let's take for example the following model: public class Event { [Required] public DateTime? StartDate { get; set; } [Required] public DateTime? EndDate { get; set; } } I would like to ensure that EndDate is greater than StartDate. I could write a custom validation attribute extending ValidationAttribute in order to perform custom validation logic. Unfortunately I couldn't find a way to obtain the model instance: public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { // value represents the property value on which this attribute is applied // but how to obtain the object instance to which this property belongs? return true; } } I found that the CustomValidationAttribute seems to do the job because it has this ValidationContext property that contains the object instance being validated. Unfortunately this attribute has been added only in .NET 4.0. So my question is: can I achieve the same functionality in .NET 3.5 SP1? UPDATE: It seems that FluentValidation already supports clientside validation and metadata in ASP.NET MVC 2. Still it would be good to know though if data annotations could be used to validate dependent properties.

    Read the article

  • ASP.NET MVC - Data Annotations - Why add a default RequiredAttribute?

    - by redsquare
    Can anyone explain why it is assumed that a non nullable type property should always have a RequiredAttribue? I am trying to write a label helper that will auto append * or change the css class so that I can indicate to the user that the field is required. However when querying the metadata the non nullable properties end up with a required attribute. MVC Source Code: protected override IEnumerable<ModelValidator> GetValidators( ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) { _adaptersLock.EnterReadLock(); try { List<ModelValidator> results = new List<ModelValidator>(); if (metadata.IsRequired && !attributes.Any(a => a is RequiredAttribute)) { //******* Why Do this? attributes = attributes.Concat(new[] { new RequiredAttribute() }); } foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) { DataAnnotationsModelValidationFactory factory; if (!_adapters.TryGetValue(attribute.GetType(), out factory)) factory = _defaultFactory; results.Add(factory(metadata, context, attribute)); } return results; } finally { _adaptersLock.ExitReadLock(); } }

    Read the article

  • When using Data Annotations with MVC, Pro and Cons of using an interface vs. a MetadataType

    - by SkippyFire
    If you read this article on Validation with the Data Annotation Validators, it shows that you can use the MetadataType attribute to add validation attributes to properties on partial classes. You use this when working with ORMs like LINQ to SQL, Entity Framework, or Subsonic. Then you can use the "automagic" client and server side validation. It plays very nicely with MVC. However, a colleague of mine used an interface to accomplish exactly the same result. it looks almost exactly the same, and functionally accomplishes the same thing. So instead of doing this: [MetadataType(typeof(MovieMetaData))] public partial class Movie { } public class MovieMetaData { [Required] public object Title { get; set; } [Required] [StringLength(5)] public object Director { get; set; } [DisplayName("Date Released")] [Required] public object DateReleased { get; set; } } He did this: public partial class Movie :IMovie { } public interface IMovie { [Required] object Title { get; set; } [Required] [StringLength(5)] object Director { get; set; } [DisplayName("Date Released")] [Required] object DateReleased { get; set; } } So my question is, when does this difference actually matter? My thoughts are that interfaces tend to be more "reusable", and that making one for just a single class doesn't make that much sense. You could also argue that you could design your classes and interfaces in a way that allows you to use interfaces on multiple objects, but I feel like that is trying to fit your models into something else, when they should really stand on their own. What do you think?

    Read the article

  • ModelMetadata: ShowForEdit property not appearing to work.

    - by Dan
    Iv wrote an MetaDataProvider like the one below and am using it in conjunction with Editor templates. The DisplayName is working correctly, but for some reason the ShowForEdit value it not having any effect. Any ideas? public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); I metadata.DisplayName = "test"; metadata.ShowForEdit = false; metadata.ShowForDisplay = false; metadata.HideSurroundingHtml = true; return metadata; } }

    Read the article

  • How can I highlight empty fields in ASP.NET MVC 2 before model binding has occurred?

    - by Richard Poole
    I'm trying to highlight certain form fields (let's call them important fields) when they're empty. In essence, they should behave a bit like required fields, but they should be highlighted if they are empty when the user first GETs the form, before POST & model validation has occurred. The user can also ignore the warnings and submit the form when these fields are empty (i.e. empty important fields won't cause ModelState.IsValid to be false). Ideally it needs to work server-side (empty important fields are highlighted with warning message on GET) and client-side (highlighted if empty when losing focus). I've thought of a few ways of doing this, but I'm hoping some bright spark can come up with a nice elegant solution... Just use a CSS class to flag important fields Update every view/template to render important fields with an important CSS class. Write some jQuery to highlight empty important fields when the DOM is ready and hook their blur events so highlights & warning messages can be shown/hidden as appropriate. Pros: Quick and easy. Cons: Unnecessary duplication of importance flags and warning messages across views & templates. Clients with JavaScript disabled will never see highlights/warnings. Custom data annotation and client-side validator Create classes similar to RequiredAttribute, RequiredAttributeAdapter and ModelClientValidationRequiredRule, and register the adapter with DataAnnotationsModelValidatorProvider.RegisterAdapter. Create a client-side validator like this that responds to the blur event. Pros: Data annotation follows DRY principle (Html.ValidationMessageFor<T> picks up field importance and warning message from attribute, no duplication). Cons: Must call TryValidateModel from GET actions to ensure empty fields are decorated. Not technically validation (client- & server-side rules don't match) so it's at the mercy of framework changes. Clients with JavaScript disabled will never see highlights/warnings. Clone the entire validation framework It strikes me that I'm trying to achieve exactly the same thing as validation but with warnings rather than errors. It needs to run before model binding (and therefore validation) has occurred. Perhaps it's worth designing a similar framework with annotations like Required, RegularExpression, StringLength, etc. that somehow cause Html.TextBoxFor<T> etc. to render the warning CSS class and Html.ValidationMessageFor<T> to emit the warning message and JSON needed to enable client-side blur checks. Pros: Sounds like something MVC 2 could do with out of the box. Cons: Way too much effort for my current requirement! I'm swaying towards option 1. Can anyone think of a better solution?

    Read the article

  • use Data Annotation to my Linq to SQL

    - by Khalid Omar
    i have a mvc web project and i'm using linq to sql i'm using dataannotaion like this public class ClientValidation { [Required] public string name1st { get; set; } } then in the linq class i add that above client class [global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.Client")] [MetadataType(typeof(ClientValidation))] public partial class Client : INotifyPropertyChanging, INotifyPropertyChanged { } every thing is going ok the question is when i re generate the linq when i add table or change any thing in database i need to rewrite [MetadataType(typeof(ClientValidation))] is there any other method to enable me regenerate the model and keep the data annotation as it

    Read the article

  • Validating only selected fields using ASP.NET MVC 2 and Data Annotations

    - by thinknow
    I'm using Data Annotations with ASP.NET MVC 2 as demonstrated in this post: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx Everything works fine when creating / updating an entity where all required property values are specified in the form and valid. However, what if I only want to update some of the fields? For example, let's say I have an Account entity with 20 fields, but I only want to update Username and Password? ModelState.IsValid validates against all the properties, regardless of whether they are referenced in the submitted form. How can I get it to validate only the fields that are referenced in the form?

    Read the article

  • change validate message in data annotation

    - by user276640
    my object has field with data type int. when i put in html form in this textbox letter not number the validator say- The field must be a number. how can i change this messages like this [Required(ErrorMessage = "??????? ????????")] [DisplayName("????????")] public int age { get; set; }

    Read the article

  • DataAnnotation attributes buddy class strangeness - ASP.NET MVC

    - by JK
    Given this POCO class that was automatically generated by an EntityFramework T4 template (has not and can not be manually edited in any way): public partial class Customer { [Required] [StringLength(20, ErrorMessage = "Customer Number - Please enter no more than 20 characters.")] [DisplayName("Customer Number")] public virtual string CustomerNumber { get;set; } [Required] [StringLength(10, ErrorMessage = "ACNumber - Please enter no more than 10 characters.")] [DisplayName("ACNumber")] public virtual string ACNumber{ get;set; } } Note that "ACNumber" is a badly named database field, so the autogenerator is unable to generate the correct display name and error message which should be "Account Number". So we manually create this buddy class to add custom attributes that could not be automatically generated: [MetadataType(typeof(CustomerAnnotations))] public partial class Customer { } public class CustomerAnnotations { [NumberCode] // This line does not work public virtual string CustomerNumber { get;set; } [StringLength(10, ErrorMessage = "Account Number - Please enter no more than 10 characters.")] [DisplayName("Account Number")] public virtual string ACNumber { get;set; } } Where [NumberCode] is a simple regex based attribute that allows only digits and hyphens: [AttributeUsage(AttributeTargets.Property)] public class NumberCodeAttribute: RegularExpressionAttribute { private const string REGX = @"^[0-9-]+$"; public NumberCodeAttribute() : base(REGX) { } } NOW, when I load the page, the DisplayName attribute works correctly - it shows the display name from the buddy class not the generated class. The StringLength attribute does not work correctly - it shows the error message from the generated class ("ACNumber" instead of "Account Number"). BUT the [NumberCode] attribute in the buddy class does not even get applied to the AccountNumber property: foreach (ValidationAttribute attrib in prop.Attributes.OfType<ValidationAttribute>()) { // This collection correctly contains all the [Required], [StringLength] attributes // BUT does not contain the [NumberCode] attribute ApplyValidation(generator, attrib); } Why does the prop.Attributes.OfType<ValidationAttribute>() collection not contain the [NumberCode] attribute? NumberCode inherits RegularExpressionAttribute which inherits ValidationAttribute so it should be there. If I manually move the [NumberCode] attribute to the autogenerated class, then it is included in the prop.Attributes.OfType<ValidationAttribute>() collection. So what I don't understand is why this particular attribute does not work in when in the buddy class, when other attributes in the buddy class do work. And why this attribute works in the autogenerated class, but not in the buddy. Any ideas? Also why does DisplayName get overriden by the buddy, when StringLength does not?

    Read the article

  • How to validate Data Annotations with a MetaData class

    - by Micah
    I'm trying to validate a class using Data Annotations but with a metadata class. [MetadataType(typeof(TestMetaData))] public class Test { public string Prop { get; set; } internal class TestMetaData { [Required] public string Prop { get; set; } } } [Test] [ExpectedException(typeof(ValidationException))] public void TestIt() { var invalidObject = new Test(); var context = new ValidationContext(invalidObject, null, null); context.MemberName = "Prop"; Validator.ValidateProperty(invalidObject.Prop, context); } The test fails. If I ditch the metadata class and just decorated the property on the actual class it works fine. WTH am I doing wrong? This is putting me on the verge of insanity. Please help.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >