2017-04-25 15 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