MVC3 Html.SelectList - 即使所选选项已更改,也始终在验证期间看到初始值

时间:2012-10-08 23:14:12

标签: c# asp.net-mvc-3

我正在创建一个用枚举值填充的选择列表:

<%= 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"))%>

1 个答案:

答案 0 :(得分:2)

我会重新考虑这个......亲自。试图将枚举破解成SelectList会产生比所需更多的工作。

简单地说,将这一切包装在ViewModel中..考虑一下:

public enum OrderStatus {
    NOT_SHIPPED,
    SHIPPED
}

public class ViewModel {
    public OrderStatus SelectedStatus { get; set; }
    public List<StatusViewModel> Models = new List<StatusViewModel>();
}

public class StatusViewModel {
    public string StringStatus { get; set; }
    public OrderStatus EnumStatus { get; set; }
}

设置(可能在控制器中......或其他地方)涉及:

ViewModel model = new ViewModel();

model.Models.Add(new StatusViewModel() { EnumStatus = OrderStatus.NOT_SHIPPED, StringStatus = "Not shipped" });
model.Models.Add(new StatusViewModel() { EnumStatus = OrderStatus.SHIPPED, StringStatus = "Shipped" });

return View(model);

..您的观点很简单:

@model Models.ViewModel
@Html.DropDownListFor(x => x.SelectedStatus, new SelectList(Model.Models, "StringStatus", "EnumStatus"))

然后,当您的模型在发布后进入时,SelectedStatus是强类型的OrderStatus枚举:

public ActionResult Index(ViewModel model) {
    // model.SelectedStatus is an OrderStatus
}