【问题标题】:Display Model Field in Razor that Matches Criteria在 Razor 中显示匹配条件的模型字段
【发布时间】:2016-02-05 03:06:20
【问题描述】:

在元素中的其他字段匹配条件的情况下,显示模型值的最佳方式是什么?例如,这是一个模型:

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

该类型模型的列表包含在 View 的 ViewModel 中:

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 = 1 Dec 2015 和 ZipCode = 12345,PriceID,其中 PriceDate = 1 Jan 2016 和 ZipCode = 12345。我已经看到了一些与此相关的问题使用 Python,但不是 Razor。我已经尝试过以下类似的方法,但都没有奏效:

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

提前致谢!

【问题讨论】:

  • 为什么不将仅与您的条件匹配的数据加载到您的操作方法中的视图模型?此外,您需要遍历 Prices 集合以获取每个属性值

标签: c# html asp.net-mvc razor


【解决方案1】:

这确实是一个 c# 问题。我建议你把这个逻辑放在别处,但这里是这样。

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

【讨论】:

  • 谢谢大家 - 我会将此标记为正确,因为它在技术上回答了问题,但我将重新设计 ViewModel。
【解决方案2】:

您应该在控制器中执行逻辑(这就是 ModelViewController (MVC) 的全部内容)。

在控制器中,您返回 PriceModel 和过滤后的价格。

您可以在控制器中按照您想要的方式过滤列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2014-10-15
    • 2013-04-20
    相关资源
    最近更新 更多