2016-02-04 53 views
-1

在元素中的其他字段與條件匹配時顯示模型值的最佳方式是什麼?例如,這裏是一個模型:在剃刀中顯示符合條件的模型字段

public class PricesModel 
{ 
    public int PriceID { get; set; } 
    public DateTime PriceDate { get; set; } 
    public int ZipCode { get; set; } 
} 

這種類型的模型的列表視圖中包含的視圖模型:

public class PricesViewModel 
{ 
    public List<PricesModel> Prices { get; set; } 
    //Additional data 
} 

並在視圖中,我們有一個表是這樣的:

@model PricesViewModel 
<table class="table"> 
    <tr class="info"> 
     <th><em>Price IDs</em></th> 
     <th>@String.Format("{0:d MMM yyyy}", new DateTime(2015,12,1))</th> 
     <th>@String.Format("{0:d MMM yyyy}", new DateTime(2016,1,1)</th> 
    </tr> 
    <tr> 
     <th scope="row" >12345</th> 
     <td></td> 
     <td></td> 
    </tr> 
</table> 

因此,表單元格中的條目爲:PriceID其中PriceDate = 2015年12月1日和ZipCode = 12345,PriceID其中PriceDate = 2016年1月1日和ZipCode = 12345。我已經看到一些與這使用Pytho n,但不是剃刀。我試過像下面的東西,但都沒有工作:

@Model.PricesModel.PriceID.Where(i => Model.PricesModel[i].ZipCode == 12345).ToString() 

在此先感謝!

+1

爲什麼不在您的操作方法中只加載符合條件的視圖模型的數據?此外,您需要遍歷Prices集合以獲取每個屬性值 – Shyju

回答

1

這真是一個C#的問題。我建議你把這個邏輯放在其他地方,但是這裏就是這樣。

@Model.Prices.FirstOrDefault(p => p.ZipCode == 12345 && p.PriceDate.Date == new DateTime(2015, 12, 1))?.PriceId 
+0

謝謝大家 - 我將標記爲正確的,因爲它在技術上回答了問題,但我將重新設計ViewModel。 – jle

0

您應該執行控制器中的邏輯(這就是ModelViewController(MVC)的全部內容)。

在控制器中,您返回PricesModel與過濾的價格。

您可以在控制器中以您想要的方式過濾列表。