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