我正在创建一个填充有枚举值的选择列表:
<%= Html.DropDownListFor(model => model.OrderStatus, new SelectList(Enum.GetValues(typeof(OrderStatus))))%>
我现在正在执行客户端验证以确保正确设置 OrderStatus:
[DisplayName("Order Status"), EnsureOrderStatus("ID")]
public OrderStatus OrderStatus { get; set; }
public class EnsureOrderStatus : ValidationAttribute, IClientValidatable
{
private readonly string OrderIDPropertyName;
public EnsureOrderStatus(string orderIDPropertyName)
{
OrderIDPropertyName = orderIDPropertyName;
}
protected override ValidationResult IsValid (object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
var propertyTestedInfo = validationContext.ObjectType.GetProperty(OrderIDPropertyName);
if (propertyTestedInfo == null)
{
validationResult = new ValidationResult(string.Format("Unknown property {0}", OrderIDPropertyName));
}
else
{
int orderID = (int)propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
OrderStatus orderStatus = (OrderStatus)value;
if (orderID == 0 && orderStatus != OrderStatus.Future)
{
validationResult = new ValidationResult(string.Format("Order must have have an Order Status of Future when being created."));
}
}
return validationResult;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "ensureorderstatus"
};
rule.ValidationParameters["orderid"] = OrderIDPropertyName;
yield return rule;
}
}
IsValid 内部的 'value' 值始终是 OrderStatus 的第一个枚举值。我想知道是否需要采取其他步骤来确保 DropDownList 元素的选定值正确更新。
更新代码:
//OrderDetailsModel:
[DisplayName("Order Status"), EnsureOrderStatus("ID")]
public OrderStatus OrderStatus { get; set; }
public List<OrderStatusModel> OrderStatusModels = new List<OrderStatusModel>();
public OrderDetailsModel()
{
OrderStatusModels.Add(new OrderStatusModel { EnumStatus = OrderStatus.Active, StringStatus = "Active" });
OrderStatusModels.Add(new OrderStatusModel { EnumStatus = OrderStatus.Completed, StringStatus = "Completed" });
OrderStatusModels.Add(new OrderStatusModel { EnumStatus = OrderStatus.Future, StringStatus = "Future" });
}
<%= Html.DropDownListFor(model => model.OrderStatus, new SelectList(Model.OrderStatusModels, "StringStatus", "EnumStatus"))%>