使用货币的输入标记帮助程序上的 asp 格式属性会导致 POST 操作出现问题



在我的ASP.NET Core 1.1, EF-Core 1.1应用程序中,我正在使用带有 asp 格式属性 ASP.NET MVC 输入标签帮助程序作为asp-format="{0:C}",它可以正确显示输入标签上的货币格式作为$15,201.45.00 ...等。但是,在过帐View时,模型仍以货币格式保留这些值,因此,正如预期的那样,下面显示的 POST 操作失败。问题:如何在发布模型之前摆脱货币格式?注意:此处提供了有关输入标记帮助程序的一些示例。

public class CustomerOrdersModelView
{
    public string CustomerID { get; set; }
    public int FY { get; set; }
    public float? item1_price { get; set; }
    public float? item2_price { get; set; }
    ...
    public float? item9_price { get; set; }
}

视图:

<form asp-controller="CustOrders" asp-action="ProductPrices" method="post">
....
<tr>
 <td>Item1:</td>
 <td><input asp-for="item1_price" asp-format="{0:C}" />></td>
</tr>
<tr>
     <td>Item2:</td>
     <td><input asp-for="item2_price" asp-format="{0:C}" />></td>
</tr>
...
<tr>
     <td>Item9:</td>
     <td><input asp-for="item9_price" />></td>
</tr><tr>
     <td>Item1:</td>
     <td><input asp-for="item1_price" asp-format="{0:C}" /></td>
</table>
<button type="submit" name="submit" value="Add">Update Report</button>
</form>

开机自检操作:[导致问题]

[GetPost]
Public ProductPrices(CustomerOrdersModelView model)
{
  ....
  recToUpdate.item1_price = model.item1_price;
  recToUpdate.item1_price = model.item2_price;
  ....
  recToUpdate.item1_price = model.item9_price;
}

在显示屏中,您可以在标签附近显示货币符号。然后以 {C:2} 格式显示字符串。

然后,模型应正确绑定值。

您是否尝试过将ModelBinderAttribute应用于模型?

例如,应用属性,然后从传入的 RAW 表单值中获取调整后的值

[ModelBinder(BinderType = typeof(CustomerOrdersEntityBinder))]
public class CustomerOrdersModelView
{
    public string CustomerID { get; set; }
    public int FY { get; set; }
    public float? item1_price { get; set; }
    public float? item2_price { get; set; }   
    public float? item9_price { get; set; }
}

public class CustomerOrdersEntityBinder : IModelBinder
{

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }
        var model = new CustomerOrdersModelView();
        if (bindingContext.ModelType != typeof(CustomerOrdersModelView))
            return TaskCache.CompletedTask;
        // Try to fetch the value of the argument by name
        var valueProviderResult =  bindingContext.ValueProvider.GetValue("item1_price");
        if (valueProviderResult == ValueProviderResult.None)
        {
            return TaskCache.CompletedTask;
        }
        model.item1_price = float.Parse(valueProviderResult.FirstValue.Replace("$",string.Empty).Replace(",",string.Empty));
        bindingContext.Result = ModelBindingResult.Success(model);
        return TaskCache.CompletedTask;
    }
}

最新更新