ASP.NET MVC - 配列を処理することができるバインダーのカスタムモデル
-
23-09-2019 - |
質問
私は、ユーザーが入力として... 10 USD、10 $、$ 10を、許可するように、すなわち、任意の形式で価格を入力できるようにする機能を実装する必要があります。
Iプライスクラス用のカスタムモデルバインダーを実装することによってこの問題を解決したいと思います。
class Price { decimal Value; int ID; }
は、フォームをキーとしてアレイまたは料金が含まれている
keys:
"Prices[0].Value"
"Prices[0].ID"
"Prices[1].Value"
"Prices[1].ID"
...
のViewModel料金プロパティが含まれています:
public List<Price> Prices { get; set; }
は、デフォルトのモデルバインダーは、限り、ユーザが入力された値に小数-コンバーチブルの文字列を入力するとうまく動作します。 私は「100ドル」のような入力を可能にしたいと思います。
私のModelBinder価格タイプのため、これまでます:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Price res = new Price();
var form = controllerContext.HttpContext.Request.Form;
string valueInput = ["Prices[0].Value"]; //how to determine which index I am processing?
res.Value = ParseInput(valueInput)
return res;
}
私はカスタムモデルバインダーを実装するにはどうすればよいことを正しくハンドルの配列?
解決
ガットは:ポイントは、単一価格のインスタンスをバインドしようとするのではなく、List<Price>
タイプのためModelBinderを実装しないことです。
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
List<Price> res = new List<Price>();
var form = controllerContext.HttpContext.Request.Form;
int i = 0;
while (!string.IsNullOrEmpty(form["Prices[" + i + "].PricingTypeID"]))
{
var p = new Price();
p.Value = Process(form["Prices[" + i + "].Value"]);
p.PricingTypeID = int.Parse(form["Prices[" + i + "].PricingTypeID"]);
res.Add(p);
i++;
}
return res;
}
//register for List<Price>
ModelBinders.Binders[typeof(List<Price>)] = new PriceModelBinder();
所属していません StackOverflow