ASP.NET MVC 4 C# に基づいて Web サイトを構築しています。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")
}
独自のモデル バインダーを作成してこのソリューションを実行しようとしましたが、これを機能させることができません。
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());