MVC3模型验证不适用于double

Vin*_*nyG 5 c# data-annotations asp.net-mvc-3

我在MVC中验证了问题,我的模型有双重属性,当我提交10.30或任何带有"."的东西时.在里面它告诉我"价值'10 .30'对价格无效".我做了一些研究,他们说模型验证应该是文化不变的,我认为它可能是问题,因为我的浏览器和服务器是法语但它不应该.

这是我的代码:

[HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        [ValidateInput(false)]
        public virtual ActionResult Edit(AuctionModel model)
        {
            if (ModelState.IsValid)
            {
                //do the work
            }
            return View(model);
        }

public class AuctionModel
    {
        public string Id { get; set; }
        [Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = "FieldMandatory")]
        [LocalizedDisplayName("Title")]
        public string Title { get; set; }
        [Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = "FieldMandatory")]
        [LocalizedDisplayName("Description")]
        public string Description { get; set; }
        [Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = "FieldMandatory")]
        [LocalizedDisplayName("Photo")]
        public string Photo { get; set; }
        [Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = "FieldMandatory")]
        [LocalizedDisplayName("StartDate")]
        public DateTime StartDate { get; set; }
        [Required(ErrorMessageResourceType = typeof(Strings), ErrorMessageResourceName = "FieldMandatory")]
        [LocalizedDisplayName("Price")]
        public double Price { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!

Vin*_*nyG 3

最后我关注了 Haacked 的这篇文章:

http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx

而且效果很好。

这是代码:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.InvariantCulture);
        }
        catch (FormatException e)
        {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
Run Code Online (Sandbox Code Playgroud)

在 global.ascx 中:

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
Run Code Online (Sandbox Code Playgroud)