下拉列表验证消息mvc

时间:2011-07-21 20:35:32

标签: validation asp.net-mvc-3 drop-down-menu razor

在我的viewModel中我有

public string Addressline1 { get; set; }
public List<SelectListItem> StateList
    {
        get
        {
            return State.GetAllStates().Select(state => new SelectListItem { Selected = false, Text = state.Value, Value = state.Value }).ToList();
        }
    }

在视图中我有

@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")

当输入AddressLine1时,状态列表DropDownList选择是必需的。如果在下拉列表中没有选择状态而不是默认的“选择”值,我如何验证并显示错误消息?

1 个答案:

答案 0 :(得分:8)

使用StateCode属性装饰[Required]属性:

[Required(ErrorMessage = "Please select a state")]
public string StateCode { get; set; }

public IEnumerable<SelectListItem> StateList
{
    get
    {
        return State
            .GetAllStates()
            .Select(state => new SelectListItem 
            { 
                Text = state.Value, 
                Value = state.Value 
            })
            .ToList();
    }
}

然后您可以添加相应的验证错误消息:

@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
@Html.ValidationMessageFor(model => model.StateCode)

更新:

好吧,您似乎希望根据视图模型上的某些其他属性有条件地验证此StateCode属性。现在这是一个完全不同的故事,您应该在原始问题中解释这一点。无论如何,一种可能性是编写自定义验证属性:

public class RequiredIfPropertyNotEmptyAttribute : ValidationAttribute
{
    public string OtherProperty { get; private set; }
    public RequiredIfPropertyNotEmptyAttribute(string otherProperty)
    {
        if (otherProperty == null)
        {
            throw new ArgumentNullException("otherProperty");
        }
        OtherProperty = otherProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(OtherProperty);
        if (property == null)
        {
            return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0} is an unknown property", new object[]
            {
                OtherProperty
            }));
        }
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null) as string;
        if (string.IsNullOrEmpty(otherPropertyValue))
        {
            return null;
        }

        if (string.IsNullOrEmpty(value as string))
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }
}

现在使用此属性装饰您的StateCode属性,如下所示:

public string AddressLine1 { get; set; }

[RequiredIfPropertyNotEmpty("AddressLine1", ErrorMessage = "Please select a state")]
public string StateCode { get; set; }

现在假设您有以下表格:

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.AddressLine1)
        @Html.EditorFor(x => x.AddressLine1)
    </div>

    <div>
        @Html.LabelFor(x => x.StateCode)
        @Html.DropDownListFor(x => x.StateCode, Model.States, "-- state --")
        @Html.ValidationMessageFor(x => x.StateCode)
    </div>

    <input type="submit" value="OK" />
}

仅当用户在StateCode字段中输入值时,才需要AddressLine1下拉列表。