0

I have a ViewModel which contains a form:

@using(Html.BeginForm())
{
     @Html.EditorFor(x=>x.Price)
     <input type="submit" value="Submit" />
}

In my Controller Action which loads this View, I have set the Price and pass it to the View. For example I've set it to 3:

public ActionResult MyAction()
{
     MyModel model = new MyModel();
     model.Price = 3;
     return View(model);
}

What I want to do, is when this form is submitted I want to check to see if the value submitted by the user is less than the original value, in this case 3. Is that possible with Model Validation? So if I input 2, then the ModelState would be invalid but if I input 4, it would be valid.

CallumVass
  • 11,288
  • 26
  • 84
  • 154

4 Answers4

0

RemoteAttribute would be fit for this I think:

on top of the price field:

[RemoteAttribute("CheckPrice", "MyController", AdditionalFields="MyModelId")]

in controller MyController:

public ActionResult CheckPrice(decimal price, int myModelId){
   //get model by id
   //return valid or invalid
   return Json(true, JsonRequestBehavior.AllowGet);
}

*Edit for server-side:

make a custom attribute which inherits RemoteAttribute & put the same logic in the IsValid method:

public class MyRemoteAttribute : RemoteAttribute
{
     public MyRemoteAttribute() : base("CheckPrice","Kenmerk"){
         base.HttpMethod = "Post";
     }

     public override bool IsValid(object value){
           //recreate validation here
           //additionalfields can be found in HttpContext.Current.Request.Params
           return true;
     }
}
kows
  • 121
  • 1
  • 7
0

why you need to post a value every time to server... check it in client side

Dasarp
  • 194
  • 1
  • 5
  • Checking client side relies on Javascript, in some cases this may be disabled so I really need a server side solution to this – CallumVass Apr 05 '12 at 07:11
0

What you would want to do is include the original value in a hidden field, such as Price_orig, then you can do any of a number of things. If you don't care about client side validation, youc an implement IValidatableObject on the model. If you want client validation, then you can implement a custom attribute that checks the value of another property, similar to the attribute described here:

Data validation with custom attributes (AttributeTargets.Class) on EF buddy classes

Another option is to use FluentValidation

Community
  • 1
  • 1
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
0

Just to let you know, I created a new Property on my Model which holds the original value, then In the Validate method on my model which implements the IValidatableObject, I've done a check to see if the new value is less than the original value. This has solved my problem

CallumVass
  • 11,288
  • 26
  • 84
  • 154