在asp.net MVC4条件验证 [英] Conditional Validation in asp.net MVC4

查看:89
本文介绍了在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的进入我的code ...

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 ...我然后设定最低长度和调用远程函数来确保该值是唯一的。

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.

这是所有我至今读,有做到这一点使用unobrtusive阿贾克斯没有明确的办法?我错了,有没有一种方法可以做到这一点?如果不是这样,我怎么能只是把普通的旧jQuery验证了我的code?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆