[英]Implement custom ModelBinder ASP.NET MVC
我遇到了很多人已經遇到的相同問題-Model Binder不接受本地化的十進制輸入。 在所有線程中,在這里和其他論壇中,推薦的解決方案是實現自定義ModelBinder
。
我的問題是這些解決方案對我不起作用。 讓我們以以下解決方案為例: asp.net mvc 5中的逗號十進制分隔符
當我引用所有名稱空間時,仍然存在兩個錯誤:
錯誤CS0115'DecimalModelBinder.BindModel(ControllerContext,ModelBindingContext)':找不到合適的方法來覆蓋...
和
錯誤CS0173無法確定條件表達式的類型,因為在'bool'和'decimal'之間沒有隱式轉換
第二個引用整個return
語句。
MVC框架中是否發生了某些更改,因此此代碼已過時,或者我做錯了什么?
我最終得到的代碼是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Mvc;
namespace AetMuzickaOprema.App_Start
{
public class DecimalModelBinder : System.Web.ModelBinding.DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, System.Web.ModelBinding.ModelBindingContext bindingContext) //first error
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue); //second error
}
}
}
有問題的模型屬性:
[Required]
[Range(typeof(decimal), "0", "999999999")]
public decimal Price { get; set; }
看來最終您想要實現的是屬性級別的綁定,例如:
[PropertyBinder(typeof(PropertyBBinder))]
public IList<int> PropertyB {get; set;}
如果是正確的話,則此帖子提供了一個解決方案: 屬性的自定義模型活頁夾
謝謝。
在ASP.NET Core 1.1(Microsoft.AspNetCore.Mvc.Core.Abstraction,1.0.1.0)中,您將看到以下界面
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
//
// Summary:
// Defines an interface for model binders.
public interface IModelBinder
{
//
// Summary:
// Attempts to bind a model.
//
// Parameters:
// bindingContext:
// The Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext.
//
// Returns:
// A System.Threading.Tasks.Task which will complete when the model binding process
// completes.
// If model binding was successful, the Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext.Result
// should have Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingResult.IsModelSet
// set to true.
// A model binder that completes successfully should set Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingContext.Result
// to a value returned from Microsoft.AspNetCore.Mvc.ModelBinding.ModelBindingResult.Success(System.Object).
Task BindModelAsync(ModelBindingContext bindingContext);
}
}
在Microsoft.AspNetCore.Mvc.ModelBinding.Binders
命名空間,程序集Microsoft.AspNetCore.Mvc.Core, Version=1.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
中定義模型綁定程序。 他們似乎都沒有公開BindModel()
方法,甚至沒有公開虛擬方法。 似乎您正在嘗試覆蓋不存在的方法。
更好的方法是采用現有的ModelBinder
,它最適合您的需求,從中繼承並重寫ModelBindAsync()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.