In my Model I have things like that :
[...]
public string PasswordConfirm { get; set; }
public string Captcha { get; set; }
[...]
I would like that these two attributes are required but not serializable
I tried tu use [required] and [nonSerialized] annontations but without success. I already saw this post
But I don't know how to do what I want. It will be helpful for NonObtrusive-Validation, i want these field complete but i don't want to serialized them.
I found a solution to my answer.
I can use the annotation [notMapped] which is compatible with [required], [compare] ...
I also use this :context.Configuration.ValidateOnSaveEnabled = false; where I filled my base because i got a problem with validation here.
Related
I am struggling to find a simple answer to this question, hopefully someone out there can help?
I have a system using MVC3 code first and EF4.1.
I have a number of models and I am trying to override DbContext.SaveChanges to provide an audit facility.
There are certain high volume columns that should be excluded from the Audit.
I had hoped that I could use the AdditionalMetadata tag like so...
public class User : IAuditable
{
[Key]
public int UserID { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
[AdditionalMetadata("IgnoreAudit", true)]
public DateTime? LastActive { get; set; }
}
and then in my audit code use something like...
bool AuditThis = ModelMetadata
.FromLambdaExpression(dbEntry.Property(propertyName), null)
.AdditionalValues("IgnoreAudit");
to determine whether to log the change or not.
Obviously this code fails as it was taken (and changed!) from a view.
My question is. Can the ModelMetaData be read outside of a ViewContext or am I barking up the wrong tree?
Thanks for taking the time to read.
I found the pointer on stackoverflow here but I needed the slightly different
var metaData = ModelMetadataProviders
.Current.GetMetadataForProperty(null, objType, propertyName);
In building an app, we created a generic object model to store some values, the viewmodel looks a bit like this at the moment:
public class FooViewModel {
public int ID { get; set; }
public byte FooType { get; set; }
[Required]
[Display(Name = "Bar Name")]
public string Name { get; set; }
[Required]
public string Email { get; set; }
//etc, etc
}
The problem is: depending on the FooType, we want to have the Display Name to be different and the Email is not required for type 1 and 2, but is required for type 3 and 4.
We tried seperating out the properties that differ per type in to classes that inherit from this one, but the validation does a fallback on what is specified in the base type, so that didn't work.
Currently, the only option seems to be to create a viewmodel for each FooType (and also seperate controllers and view), which leads to a lot of code duplication.
What are other ways to keep this DRY?
To benefit a validation context (e.g. validating objects in different contexts), I strongly recommend using FluentValidation library.
You could implement a custom RequiredIf validation attribute, or you could implement IValidatableObject.
I have a ViewModel that has been deserialized from JSON which looks something like this:
public class UserThingsUpdateViewModel
{
public IList<Thing> Things { get; set; }
[Required]
public int UserId { get; set; }
public int Age { get; set; }
}
Thing is also a ViewModel which also has various DataAnnotaion ValidationAttribute attributes on the properties.
The problem is that Lists don't seem to get validated and even after a through search I cant seem to find any articles that tackle this. Most suggest that the ViewModel is wrong if it includes a list.
So, what is the best way to validate my list and add Model Errors to the Model State?
Prior to checking ModelState.IsValid, you could add code to step through and validate each Thing, as follows:
foreach (var thing in Things)
TryValidateModel(thing);
This will validate each item, and add any errors to ModelState.
You could write a custom validator attribute and decorate the list property with it? That would allow you to write custom logic to get the elements out of the list and validate them.
i have a tables Service with "Price" and "Discount" fields and ServiceLanguage with "Name" and "Description" fields. in the View i using ServiceLanguage as a model. so i create a partial class for validation.
public string Name { get; set; }
public string Description { get; set; }
this works greate. but also i need to validate Price and Discount
public expm_Service expm_Service.MaxDiscount{ get; set; }
public expm_Service expm_Service.Price { get; set; }
and this doesn't work greate. the problem is:
Error 1 The modifier 'public' is not
valid for this item
how can i validate Price and Discount? any help?
Not sure if this is what your after, as its a bit hard to understand your question, but check out this link, it describes attribute based validation on your model. Then you can apply that to your Price and Discount properties.
It looks like your trying to declare two properties into your model from "expm_Service". The declarations don't make much sense.
You need to add MaxDiscount and Price to your model in the same way as you've done for Name and Description. Then you can pass the values to and from the model via your service.
E.g.
public string MaxDiscount { get; set; }
public string Price { get; set; }
Plus any DataAnnotations to set validation rules on those.
Is there an attribute I can decorate a single property on my model to tell the engine not to include the property in the validation routine?
[DoNotValidate] or [ValidateIgnore]
----------------------More info.
Ok, I need to give you more information. In my situation, I have a temporary decimal value on my model that is not persisted, that gets formatted into currency. $540,000.
In this one case I do not want to strip the formatting out before I call TryUpdateModel. When you use TryupdateModel, it mvc will try and convert that string text box value back into a decimal and Model.IsValid will return false. I know how to get around this situation, using javascript, but it would be easier if I could tell mvc not to validate that field.
Any model properties not decorated with validation attributes should be ignored.
public class MyModel
{
[Required]
public string SomeProperty { get; set; }
public string IgnoredProperty { get; set; }
}
Should validate that SomeProperty is required, but nothing will happen with IgnoredProperty.
The best tutorial IMHO on Model validation is http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
(even though it says for MVC 2, it's applicable).
Change the type of your decimal to nullable decimal to prevent required validation:
public class MyModel
{
public decimal MyValidatingDecimal { get; set; }
public decimal? MyNonValidatingDecimal { get; set; }
}
MyValidatingDecimal will be required (since it is a value-type), while MyNonValidatingDecimal will not be required.
Properties will only be validated if you explicitly apply validation attributes to them.