asp.net MVC4 中的条件验证 [英] Conditional Validation in asp.net MVC4
问题描述
我希望能够根据调用视图的控制器启动一些验证功能......我将在 ViewState 或其他东西中设置一个变量,这将帮助我知道这个视图是从哪个控制器调用的.
I want to be able to kick off some validation functions based upon what controller a view is called from... I will set a variable in ViewState or something and that will help me to know what controller this view was called from.
换句话说,如果设置了某个变量,我希望验证是必需的...这是我在 MVC2 中使用的方法,当我将 Jquery 放入我的代码中时...
In other words, I want the validation to be required if a certain variable is set... Here is how I use to do in MVC2 when I just put Jquery into my code...
HospitalFinNumber: {
required: function (element) {
debugger;
return '@isFlagSet' != 'True';
},
minlength: 6,
remote: function () {
//debugger;
return {
url: '@Url.Action("ValidateHosFin", "EditEncounter")',
data: { hospitalFin: $('#HospitalFinNumber').val(), encflag: '@encflag' }
};
}
}
你看我在那里做什么.仅当设置了某个变量时才需要此验证...在这种情况下,变量 isFlagSet... 然后我将设置 min Length 并调用远程函数以确保该值是唯一的.
You see what I am doing there. This validation would only be required if a certain variable is set... In this case, the variable isFlagSet... I would then set min Length and call a remote function to ensure that the value is unique.
我不想在所有情况下都这样做.
I don't want to do this in all cases.
从我目前阅读的所有内容来看,没有明确的方法可以使用不显眼的 ajax 来实现这一点吗?我错了,你有办法做到这一点吗?如果没有,我如何将常规的旧 jquery 验证放入我的代码中?
From all I have read so far, there is no clear way to accomplish this using unobrtusive ajax? Am I wrong, is there a way you can do this? If not, how can I just place regular old jquery validation into my code?
推荐答案
ASP.NET MVC 3 使用 jquery 非侵入式验证来执行客户端验证.因此,您可以编写 自定义 RequiredIf
验证属性或使用 Mvc 万无一失验证 然后:
ASP.NET MVC 3 uses jquery unobtrusive validation to perform client side validation. So you could either write a custom RequiredIf
validation attribute or use the one provided in Mvc Foolproof Validation and then:
public class MyViewModel
{
[RequiredIf("IsFlagSet", true)]
[Remote("ValidateHosFin", "EditEncounter")]
[MinLength(6)]
public string HospitalFinNumber { get; set; }
public bool IsFlagSet { get; set; }
public string EncFlag { get; set; }
}
然后剩下的就是包含 jquery.validate.js
和 jquery.validate.unobtrusive.js
脚本或在 ASP.NET MVC 4 中使用相应的包包括他们.
Then all that's left is to include the jquery.validate.js
and jquery.validate.unobtrusive.js
scripts or use the corresponding bundle in ASP.NET MVC 4 that includes them.
这篇关于asp.net MVC4 中的条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!