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

时间:2013-07-23 21:41:14

标签: asp.net-mvc asp.net-mvc-4 modelstate

我正在构建一个基于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; }
}

我的观点

@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")
}

我试图通过创建自己的模型绑定器来关注this solution,但我无法让它工作。

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;
        }
    }
}

在Global.asax.cs Application_Start()中添加了一行:

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());

1 个答案:

答案 0 :(得分: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;
    }
}

并且,在Global.asax.cs的{​​{1}}:

Application_Start()

您不需要ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder()); 。你可以删除它。