我正在使用 Steve SandersonsBeginCollectionItem
扩展来帮助绑定项目列表。这适用于原始类型。我遇到的问题是,对于我编写的自定义模型绑定器,我看不到如何生成我要绑定的项目的全名和索引。
目前我的模型活页夹看起来像这样:
public class MoneyModelBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Amount");
if (valueResult != null)
{
var value = valueResult.AttemptedValue;
var currencyCode = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Iso3LetterCode").AttemptedValue;
var money = (Money) bindingContext.Model;
Money parsedValue;
if (String.IsNullOrEmpty(value))
{
money.Amount = null;
return;
}
var currency = Currency.FromIso3LetterCode(currencyCode);
if (!Money.TryParse(value, currency, out parsedValue))
{
bindingContext.ModelState.AddModelError("Amount", string.Format("Unable to parse {0} as money", value));
}
else
{
money.Amount = parsedValue.Amount;
money.Currency = parsedValue.Currency;
}
}
else
{
base.OnModelUpdated(controllerContext, bindingContext);
}
}
}
我的 ViewModel Lokks 是这样的(为清楚起见,省略了一些属性):
public class EditFeeEarningCapacityViewModel
{
public List<FeeEarner> FeeEarners { get; set; }
public class FeeEarner
{
public Money AverageChargeOutRate { get; set; }
}
}
我的 Money 类型的编辑模板如下所示:
@model Core.Money
@{
int decimalPlaces;
if(!int.TryParse(string.Format("{0}", ViewData["DecimalPlaces"]), out decimalPlaces))
{
decimalPlaces = 0;
}
}
<div class="input-prepend">
<span class="add-on">@Model.Currency.Symbol</span>@Html.TextBoxFor(m => m.Amount,
new
{
placeholder = string.Format("{0}", Model.Currency),
@class = "input-mini",
Value = String.Format("{0:n" + decimalPlaces + "}", Model.Amount)
})
</div>
@Html.HiddenFor(x => x.Iso3LetterCode)
对于具有这样的 post 值的表单:
FeeEarners.index 3fa91d09-0617-4bea-ae3f-d84862be8c04
FeeEarners[3fa91d09-0617-4bea-ae3f-d84862be8c04].feeEarner.AverageChargeOutRate.Amount 500
FeeEarners[3fa91d09-0617-4bea-ae3f-d84862be8c04].feeEarner.AverageChargeOutRate.Iso3LetterCode GBP
我看不到如何检测项目的索引或我绑定到的属性名称。所以本质上,我如何找到我试图绑定到的项目的索引和我试图绑定数据的属性的名称?