gpt4 book ai didi

validation - 下拉列表验证消息 mvc

转载 作者:行者123 更新时间:2023-12-01 09:36:28 25 4
gpt4 key购买 nike

在我的 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 选择是必需的。当下拉列表中除了默认的“选择”值之外没有选择任何状态时,如何验证并显示错误消息?

最佳答案

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

[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)

更新:

好吧,您似乎想根据 View 模型上的其他属性有条件地验证此 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" />
}

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

关于validation - 下拉列表验证消息 mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6782410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com