TJK*_*TJK 3 validation razor asp.net-mvc-3 drop-down-menu
在我的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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来
@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
Run Code Online (Sandbox Code Playgroud)
当输入AddressLine1时,则状态列表DropDownList选择是必需的.如果在下拉列表中没有选择状态而不是默认的"select"值,我如何验证并显示错误消息?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以添加相应的验证错误消息:
@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
@Html.ValidationMessageFor(model => model.StateCode)
Run Code Online (Sandbox Code Playgroud)
更新:
好吧,您似乎希望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;
}
}
Run Code Online (Sandbox Code Playgroud)
现在StateCode使用此属性装饰您的属性,如下所示:
public string AddressLine1 { get; set; }
[RequiredIfPropertyNotEmpty("AddressLine1", ErrorMessage = "Please select a state")]
public string StateCode { get; set; }
Run Code Online (Sandbox Code Playgroud)
现在假设您有以下表格:
@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" />
}
Run Code Online (Sandbox Code Playgroud)
在StateCode下拉菜单会只有当用户输入一个值到所需AddressLine1领域.
| 归档时间: |
|
| 查看次数: |
15453 次 |
| 最近记录: |