一个属性的ASP:NET MVC 4动态验证取决于另一个属性的当前值 [英] ASP:NET MVC 4 dynamic validation of a property depending of the current value of another property

查看:59
本文介绍了一个属性的ASP:NET MVC 4动态验证取决于另一个属性的当前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到一种方法来根据同一模型中另一个属性的当前值动态地验证属性.我搜索了很多东西,却找不到答案或类似的例子.

I have a problem finding out a way to validate dynamically a property depending of the current value of another property in the same model. I have searched a lot and was not able to find an answer or similar example.

在我的模型中,我有一个邮政编码属性和一个countryID属性.在每个国家/地区的数据库中,我都有一个不同的正则表达式来验证邮政编码.然后,使用countryID我可以从数据库中获取适当的正则表达式来验证相应国家/地区的邮政编码

In my model I have a zip code property and a countryID property. In the DB for each different country I have a different regex to validate the zip code. Then with the countryID I can get from the DB the apropiate regex to validate the zip code of the corresponding country

因此在我的模型中,我希望根据当前countryID的值来验证zip字段.

So in my model, depending on the value of the current countryID I want to have the validation of the zip field.

我尝试创建自定义验证属性"ZipValidation(countryID)",但是在模型中,它不允许我将另一个属性的值作为参数:

I tried creating a custom validation attribute "ZipValidation(countryID)", but in the model it doesn't let me have the value of another property as a parameter:

public class AddressViewModel
{
    ...
    [Display(Name = "Country ID")]
    public Guid? countryID { get; set; }

    [Required]
    //[ZipValidation(countryID)] does not compile because of the countryID
    [Display(Name = "Zip")]
    public string zip { get; set; }

}

有什么想法可以实现吗?

Any idea how this can be achieved?

推荐答案

我终于用Jonesy建议的 [Remote] 验证属性,并在控制器中使用了Json和Ajax,终于解决了它.是这样的:

I've resolved it finally with the [Remote] validation attribute as Jonesy suggested, and with Json and Ajax in my controller. It is something like that:

public class AddressViewChannelModel
{
    ....
    [Display(Name = "CountryID")]
    public Guid? countryID  { get; set; }

    [Required]
    [Remote("ValidateZipCode", "Address", AdditionalFields = "countryID")]
    [Display(Name = "Zip")]
    public string zip { get; set; }
}

public class AddressController : Controller
{
  ...
    public JsonResult ValidateZipCode(string zip, string countryID)
    {
        ValidationRequest request = new ValidationRequest();
        request.CountryID = Guid.Parse(countryID);
        request.Zip = zip;

        ValidationResponse response = new ValidationResponse();
        response = _addressApi.ZipValidation(request);

        if(response.IsSuccessful == false)
        {
            return Json("Not a valid zip code for your chosen country!"),  JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
}

这篇关于一个属性的ASP:NET MVC 4动态验证取决于另一个属性的当前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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