Client side validation mvc dropdown

跟風遠走 提交于 2019-12-24 02:00:09

问题


@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


回答1:


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/



来源:https://stackoverflow.com/questions/19904976/client-side-validation-mvc-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!