对于double值,ASP.NET MVC4 ModelState.IsValid为false

Kar*_*sen 1 asp.net-mvc modelstate asp.net-mvc-4

我正在构建一个基于ASP.NET MVC 4 C#的网站.当weight是double时,我在使用@ Html.EditorFor(model => model.Weight)时遇到了问题.如果我只输入数字到文本域ModelState.IsValid返回true.如果我输入用逗号分隔的数字,则客户端验证表明这不是有效数字.如果我输入用点分隔的数字,则客户端验证是可以的,但在服务器端,ModelState.IsValid返回false.

这是我想编辑的模型(由实体框架生成,基于数据库表):

using System;
using System.Collections.Generic;

public partial class Record
{
    public int Id { get; set; }
    public int ExerciseId { get; set; }
    public double Weight { get; set; }
    public System.Guid UserId { get; set; }
    public System.DateTime CreatedDate { get; set; }

    public virtual Exercise Exercise { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的看法

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

    <div class="editor-field">
        @Html.DropDownList("ExerciseId")
        @Html.ValidationMessageFor(model => model.ExerciseId)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Weight)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Weight) //this is the issue
        @Html.ValidationMessageFor(model => model.Weight)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.CreatedDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.CreatedDate)
        @Html.ValidationMessageFor(model => model.CreatedDate)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Run Code Online (Sandbox Code Playgroud)

我试图通过创建自己的模型绑定器来遵循此解决方案,但我无法使其工作.

DecimalModelBinder.cs

 using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TrainingLog.Helper
{
    public class DecimalModelBinder : DefaultModelBinder
    {
        public override 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;
        }
    }

    public class EFModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(Type modelType)
        {
            if (modelType == typeof(decimal))
            {
                return new DecimalModelBinder();
            }
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Global.asax.cs中添加的行Application_Start():

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

ata*_*ati 5

您的Weight属性是类型double,但您已为该类型创建了模型绑定器decimal.

将模型绑定器更改为:

public class DoubleModelBinder : DefaultModelBinder
{
    public override 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.ToDouble(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.asax.csApplication_Start():

ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
Run Code Online (Sandbox Code Playgroud)

你不需要EFModelBinderProvider.你可以删除它.