2017-04-25 16 views
0

我搜索了很多。也许我看错了地方...视图组件上的货币格式失败 - 解决办法?

我在产品列表中有产品清单和成本价格。从模型提取:

[Display(Name = "Cost Price")] 
    [DataType(DataType.Currency)]  
    public decimal CostPrice { get; set; } 

我在这个级别使用数据类型,它工作正常。

然后我引用Kitset模型中的产品模型。一个kitset是一个产品的集合来制造一个完整的解决方案。一个真实世界的例子可以是轮胎,车轮,车轮螺母和轮毂盖。

public class ProductKitset 
{ 
    public int ProductKitsetID { get; set; } 

    [Display(Name ="Kitset Name")] 
    public int ProductKitsetNameID { get; set; } 

    public decimal Quantity { get; set; } 

    [Display(Name = "Product")] 
    public int ProductID { get; set; } 

    public Product Product { get; set; } 

    public ProductKitsetName ProductKitsetName { get; set; } 
} 

然后像某些人想的报价和报价可以包括一个或多个成套工具,我的第三个模型QuoteToKitset:

public class QuoteToKitset 
{ 
    public int QuoteToKitsetID { get; set; } 

    public int QuoteID { get; set; } 

    public int ProductKitsetID { get; set; } 

    public Quote Quote { get; set; } 

    public ProductKitset ProductKitset { get; set; } 
} 

在这条产业链,然后我有一个ViewComponent结束。 ViewComponent返回报价中kitset中包含的产品的列表。目的是让准备报价的人可以看到套件中的内容,以防他们需要添加其他项目。回到我们的车轮实例,也许还需要一个盘式制动器转子。

这工作很好,只要它去,并返回我想要的结果。为了完整的viewComponent:

public class ProductKitsetsViewComponent : ViewComponent 
{ 
    private readonly Eva804Context _context; 

    public ProductKitsetsViewComponent(Eva804Context context) 
    { 
     _context = context; 
    } 

    public IViewComponentResult Invoke(int id) 
    { 
     var productKitset = from p in _context.ProductKitset 
        .Include(p=>p.Product) 
        .Where(p => p.ProductKitsetNameID == id)      
        select p; 

     return View(productKitset); 
    } 

} 

然后在该ViewComponent的默认视图我有:

@foreach (var p in Model) 
    { 
     <tr> 
      <td> 

       @p.Product.ProductCode 
      </td> 
      <td> 

       @p.Quantity 
      </td> 
      <td> 
       @p.Product.ProductDescription.Substring(0, Math.Min(p.Product.ProductDescription.Length, 38)) 
      </td> 

      <td> 

       @p.Product.CostPrice 
      </td> 

正如我说这是工作的罚款。除了成本价格的格式。在阅读本文时,我仍然在学习如何进入这个复杂的世界,成本价格格式由产品模型中的DataType设置。

在现实世界中,格式不会在ViewComponent中复制。

为什么数据类型被忽略? 我该如何解决这个问题? 在我的思考中有什么不正确的地方,我错过了这里的工作原理吗?

+0

你得到什么格式?输出是什么? –

+0

抱歉,没有注意到此评论。我只是得到原生的十进制格式,没有应用格式。我不知道为什么会发生这种情况,但下面的问题解决了它。 – BitLost

回答

0

有几种方法可以做到这一点。

@p.Product.CostPrice.ToString("C") 

在格式C无二Currency。如果你想指定格式(美元,欧元,英镑...),你可以参考this

另一种方式是指定DisplayFormat属性:

[DisplayFormat(DataFormatString = "{0:C}")] 

[DisplayFormat(DataFormatString = "${0:#,###0.00}")] 

根据this SO question

+0

@ p.Product.CostPrice。ToString(“C”)有效。为了兴趣,我尝试了模型中的DisplayFormat,但是当通过这个过程传递给ViewComponent时失败了。 – BitLost