MVC DataAnnotations - Require at least one field in a group to be filled - validation

How can I use DataAnnotations to validate that at least one of these fields are filled in?
public string Name { get; set; }
public string State { get; set;}
public string Zip { get; set;}

To do it using DataAnnotations you will need to make a custom attribute because as far as I know there is no built in attribute that will handle this.
To get you started, when you start a new MVC project there is a class called "PropertiesMustMatchAttribute" that is applied at the class level. You could base it off that without much difficulty

Related

Giving error while creating partial class

I am developing MVC application in which , I am trying to create the partial class of class generated by MVC application lets say Location class.
Now I want to create the partial class of Location class in new class file.
The below class code is auto genrated by MVC of Location code.
namespace CRM
{
public partial class Location
{
public int Id { get; set; }
public string Name { get; set; }
public string Remark { get; set; }
}
}
I have added new class file which contain the partial class of above file
namespace CRMEntities.Partial_Class
{
public interface ILocation
{
[StringLength(50, ErrorMessage = "Region can accept maximum 50 characters.")]
string Region { get; set; }
[Key]
int Id { get; set; }
[Required]
string Name { get; set; }
string Remark { get; set; }
}
public partial class Location : ILocation
{
}
}
Its giving the below error...
CRMEntities.Partial_Class.Location' does not implement interface member 'CRMEntities.Partial_Class.ILocation.Name
First, you don't need to do this, what I understand is you are trying to do validation right? Think about, the object generated by EF is not ViewModel, they are domain model. Data annotation should be in View Model, not domain model.
Most of cases, often mis-use is to use domain model as view model, but it is not correct much. Because sometime, view models need more than one domain model to provide data for your UI.
So for separation of concerns, you need to define your View Model different with domain model.
Example: you have Location class, you need to add LocationViewModel class and put data annotation in here.
You can map manually or use AutoMapper for mapping bettween View Model and Domain Model.
Another solution is you can use Fluent Validation, with this way, needless to have more partial class just for validation.
You don't show the definition of ILocation in your question, but the error says that the Location.Name property is declared differently than the ILocation.Name member.
Edit: Your two partial classes appear to be in two different namespaces, hence they are actually two entirely different classes, not two parts of the same class. That would explain the compiler error.
Having said that, I do agree with the other answer (+1!) that you should do your UI validation on a view model instead.

In ASP.NET MVC3 how do you stay DRY with very similar but slightly different viewmodels?

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.

MVC3 - Recommended way to create fields for IEnumerables with Editor Templates

I want to create a form for an entity. One of the members is an IEnumerable of a different type (that also has an IEnumerable member), for example:
public class Person
{
public string Fullname { get; set; }
public int Age { get; set; }
public IEnumerable<Position> Jobs { get; set; }
}
public class Position
{
public string Title { get; set; }
public IEnumerable<string> PhoneNumbers { get; set; }
}
I'm trying to find a good example of creating multiple fields in the html, how would I allow to enter more than one position? I think I read somewhere about someone who's cloning that part of the form with jQuery - is that the way to go?
Thanks
This blog post talks about editing a variable length list and may be what you are after.
Possible duplicate of Editing a Variable Length List, ASP.NET MVC 3 Style with Table
I personnally use an improved version of BeginCollectionItem, but I find it still too complicated when used with child views.
This is a great fail of ASP.NET MVC promises (it should be simple, fluid and powerful).

Decorating serializable class with extra properties

I'm building a Windows Phone 7 application and I'm trying to decorate a generated class with an additional property to bind against, but I'm a bit puzzled on how to solve this architecturally. What I currently have is this class, which is generated with the xsd.exe tool from an XML file:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.Diagnostics.DebuggerStepThroughAttribute]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Session
{
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Abstract { get; set; }
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Speaker { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute]
public string TimeslotBegin { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute]
public string Location { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute]
public string TimeslotEnd { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute]
public string Title { get; set; }
}
I am fetching the XML from the web and deserializing this with a XmlSerializer, but I want to add an additional property to allow the user to "flag" items in the UI. I want to be able to bind to this property, so it should notify the UI thread when changed.
Any ideas on how to solve this?
For this situation, I'd recommend you separate your Model from your ViewModel.
The ViewModel is a data representation (including bindable properties) specifically designed for your UI.
The Model is the "pure" data representation, specifically designed for modelling your domain and for persistance (either directly to IsolatedStorage or perhaps persisted via a web service)
So, my recommendation is that you build some ViewModel classes for your UI to bind to - and then work out how these ViewModels interact with the Model.
As an aside, I'd also be cautious about using the XSD generated classes within Windows Phone 7 - WP7 seems to prefer the XDocument Linq XML classes, rather than the XmlDocument XML classes (but I may have this wrong!)

ASP.NET - MVC3 property decoration?

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.

Resources