gpt4 book ai didi

c# - 客户端验证 mvc 下拉菜单

转载 作者:太空宇宙 更新时间:2023-11-03 13:32:49 26 4
gpt4 key购买 nike

@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"/>
}

我需要验证“ForatFrom”下拉值是否大于“ForatTo”值。我想我不能使用模型验证,因为那只会检查下拉列表的值是否为特定数字。我在想也许 jquery 验证但不确定最好的选择是什么?

谢谢

最佳答案

您可以而且应该使用模型验证。我会实现一个验证属性 [LargerThan],像这样:

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");
}
}

请注意,此代码未经测试,但如果您沿此行编写一些内容并将其放在单独的类中,则可以在需要进行此类检查时重用它。您现在可以将它放在模型中的属性上

public double ForatFrom { get; set; }

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

现在您有了服务器模型验证,如果您愿意,您现在可以实现 jQuery 非侵入式验证。在我看来,如果你需要验证,你应该至少在服务器上做,如果你需要在客户端做,那么也在那里实现它,但绝不能只依赖客户端验证。

这是一篇您可以阅读的好文章,它将向您展示我刚刚做了什么,并解释了如何实现客户端验证:http://thepursuitofalife.com/asp-net-mvc-3-unobtrusive-javascript-validation-with-custom-validators/

关于c# - 客户端验证 mvc 下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19904976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com