2

我正在构建一个基于 ASP.NET MVC 4 C# 的网站。当重量是双倍时,我在使用 @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")
}

我试图通过创建自己的模型活页夹来遵循这个解决方案,但我无法让它工作。

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());
4

1 回答 1

6

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

将您的模型绑定器更改为:

public class DoubleModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        object actualValue = null;
        try
        {
            actualValue = Convert.ToDouble(valueResult.AttemptedValue, CultureInfo.InvariantCulture);
        }
        catch (FormatException e)
        {   
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, e);
        }    
        return actualValue;
    }
}

而且,在你Global.asax.csApplication_Start()

ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());

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

于 2013-07-24T01:52:43.587 回答