简体   繁体   中英

Client side validation mvc dropdown

@using (Html.BeginForm("ForatExcel", "ForatSummary", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.DropDownList("ForatFrom", new SelectList(Model, "ID", "ID", new { onchange = "getAllData()" }))
@Html.DropDownList("ForatTo", new SelectList(Model, "ID", "ID", new { onchange = "getAllData()" }))
<br />
<input type="submit" id="btnForatVersion" value="Go"/> 
}

I need to validate that the "ForatFrom" dropdown value is greater than that of the "ForatTo" value. I guess i can't use model validation, as that would just check that the value of the drop down is a particular number. I was thinking maybe jquery validation but not sure what the best option would be?

Thanks

You can and should use model validation . I would implement a validation attribute [LargerThan], something like this:

public class LargerThanAttribute: ValidationAttribute, IClientValidatable
{
     private string _listPropertyName { get; set; }

     public LargerThanAttribute(string listPropertyName)
     {
         this._listPropertyName = listPropertyName;
     }

     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
     {
        if(value == null)
            return new ValidationResult("Not a valid value");

        var listProperty = validationContext.ObjectInstance.GetType().GetProperty(_listPropertyName);
        double propValue = Convert.ToDouble(listProperty.GetValue(validationContext.ObjectInstance, null));

        if(propValue <= Convert.ToDouble(value))
            return ValidationResult.Success;

        return new ValidationResult("End value is smaller than start value");
    }
}

Note that this code is not tested but if you write something along this line and put it in a seperate class, you can reuse it when ever you need to do this kind of check. You can now put it on a property in your model

public double ForatFrom { get; set; }

[LargerThan("ForatFrom")]
public double ForatTo { get; set; }

Now you have the server model validation, and if you like you can now implement jQuery unobtrusive validation. In my opinion, if you need validation, you should do it atleast on the server and if you need to do it on the client, then implement it there aswell, but never only rely on client validation.

Here's a good post that you can read that will show you what i just did and also explain how to implement client validation: http://thepursuitofalife.com/asp-net-mvc-3-unobtrusive-javascript-validation-with-custom-validators/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM