提交表单时,模型仅适用于给定方案 [英] Model Required value for only given scenario when form is submitted

查看:60
本文介绍了提交表单时,模型仅适用于给定方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注册页面,询问您给定的国家和地区.当您来自像美国这样的州时,一切都很好,但是当您来自没有州的国家时,我想将州字段保留为空白,并且仍然允许您注册和提交页面静止.

I have a registration page that asks for your given Country and State. This is all fine and dandy when you are from a Country that has states like in the U.S, but when you are from a country that doesn't have states I would like to leave the state field blank and still allow you to register and submit the page still.

在我的国家(地区)数据库表中,我有一个列集boolean(如果有状态,则为true),如果没有则为false.这样,当某人选择一个带有州名的国家时,它会将州名加载到下拉菜单中.

In my DB table for Country I have a column set boolean true if they have states and false if they don't. This way when someone selects a country with states it loads the states in the drop down menu.

我已经建立了这样的模型.

I have the model set up like such.

      [Required(ErrorMessage = "State is required.")]                
      public string StateId { get; set; }

我试图使该值可为空,但这似乎没有任何作用.那么,甚至可以使用DataAnnotations进行这样的验证吗?

I tried to make the value nullable but that seem to have no effect. So Is it even possible to do validation like this using DataAnnotations?

推荐答案

正如r3plica所说,您可以创建一个自定义验证方法来检查状态.在自定义验证方法中,您可以查询数据库并检查国家/地区是否有州,然后返回验证结果.代码如下:

As r3plica said, you could create a custom validation method to check the state. In the custom validation method, you could query the database and check whether the country has state and then return the validation result. Code as below:

public class DeveloperViewModel
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Name is Required")]
    public string Name { get; set; }
    [Required(ErrorMessage ="Country is Required")]
    public string Country { get; set; }
    [RequiredIfHasState("Country", ErrorMessage ="State is Required")]
    public string State { get; set; }
}

public class RequiredIfHasStateAttribute : ValidationAttribute
{
    private readonly string _comparisonProperty;

    public RequiredIfHasStateAttribute(string comparisonProperty)
    {
        _comparisonProperty = comparisonProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        ErrorMessage = ErrorMessageString;

        //get entered state value
        var stateValue = (string)value;
        var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
        if (property == null)
            throw new ArgumentException("Property with this name not found");
        //get the country value
        var countryValue = (string)property.GetValue(validationContext.ObjectInstance);
        //get the current dbcontext
        var _context = (MvcMovieContext)validationContext.GetService(typeof(MvcMovieContext));
        //query the database and check whether the country has state.
        if (_context.Countries.Where(c => c.CountryCode == countryValue).Select(c => c).FirstOrDefault().HasState)
        {
            if(stateValue == null)
            { 
                //if country has state and the state is null. return error message
                return new ValidationResult(ErrorMessage);
            }
            else
            {
                //if country has state and the state is not found.
                if(!_context.Countries.Where(c => c.CountryCode == countryValue).Any(c => c.States.Any(e => e.StateName == stateValue)))
                {
                    return new ValidationResult("State not found");
                }
            }
        }   
        return ValidationResult.Success;
    }
}

以下屏幕截图( GB 国家不包含州, US 国家具有州):

The screenshot as below (GB country doesn't contain state, the US country has states):

这篇关于提交表单时,模型仅适用于给定方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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