tags:

views:

736

answers:

3

I am using server side validation like

 public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name))
            yield return new RuleViolation("Name is Required", "Name");
        if (Price == 0)
            yield return new RuleViolation("Price is Required", "Price");
        yield break;
    }

When I left Price as blank, Then It takes 0 as a value.

So I check it with 0.

In my Database Price cannot be null; and I am using LINQ-to-SQL class.

Now my problem is when I left Price blank it gives me two messages.e.g.

  • A value is required.
  • Price is Required.

So How do I put custom validation without showing first error message?

Relpy to comment I am reffering book code of Professional Asp.net MVC 1.0 here.

HTML pages of Book are Here.

usefull page.

public class RuleViolation
    {
        public string ErrorMessage { get; private set; }
        public string PropertyName { get; private set; }

        public RuleViolation(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }

        public RuleViolation(string errorMessage, string propertyName)
        {
            ErrorMessage= errorMessage;
            PropertyName = propertyName;
        }
    }
+3  A: 

I think you get the first message "A value is required" automatically from the framework because your Price property is a value type, which can never be null.

So when you post a blank field, the framework will usually try to assign null to this property, which is not possible in this case.

If you change the type to nullable:

public double? Price { get; set; }

That particular message should disappear. Then you could change your validation to:

    if (Price == null)
        yield return new RuleViolation("Price is Required", "Price");

The fact that the database field does not allow nulls should not interfere with your viewmodels.

Thomas Eyde
A: 

That's because the Default Model Binder adds that error. You can write your own model binder for that particular object and work directly with the form collection to get more control over validation.

çağdaş
+2  A: 

To make what Thomas Eyde wrote above work (without messing with the code), you can...

  1. Open the corresponding .dbml file
  2. Click the "Price" property
  3. In the Visual Studio Properties window, change the Nullable value from False to True
  4. Save the file!

You can now go into your class and add the if statement and VS should not complain.

robnardo
Well, Right now I don't have that code, But your answer seems perfect.
Vikas