在MVC EF显示名称两个标签之间进行动态选择 [英] dynamically choose between two labels for the Display Name in mvc ef

查看:155
本文介绍了在MVC EF显示名称两个标签之间进行动态选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架,MVC。如何可以动态两个标签用于一个数据字段之间变化(基于从另一个数据库中检索有关同一车辆数据)?我非常希望我的模型类有它这样的事情(这是伪code和预计不会编译):

I am using Entity Framework, MVC. How can I dynamically change between two labels for one data field (based on data retrieved from another database about the same vehicle)? Ideally I would like my Model class to have something like this in it (this is pseudocode and is not expected to compile):

[Display(Name = "resCatalyst", ResourceType = typeof(VehiclesModelResource))]
    public string Catalyst { get; set; }
...
public void SetElementDisplayName(bool DieselOlderThan2009)
    {
        if (DieselOlderThan2009)
        {
            Catalyst.SetDisplayName(Name = "resNMHCCatalyst", ResourceType = typeof(VehiclesModelResource));
        }
        else
        {
            Catalyst.SetDisplayName(Name = "resCatalyst", ResourceType = typeof(VehiclesModelResource));
        }
    }

我也想改变标签的CSHTML文件中像这样的:

I did think of changing the label in the cshtml file like this:

@if(Model.vltDataOne.FuelType == "D" && Model.vltDataOne.VehicleYear >= 2009)
            {
                <p>
                        <b> @Html.LabelFor(model => model.testObd.Catalyst, @DTResource.resNMHCCatalyst) </b>
                        @Html.DisplayFor(model => model.testObd.Catalyst) 
                </p>
            }
else
            {
                <p>
                        <b> @Html.LabelFor(model => model.testObd.Catalyst, @DTResource.resCatalyst) </b>
                        @Html.DisplayFor(model => model.testObd.Catalyst) 
                </p>
            }

但我响应业务规则,我真的觉得应该是在模型中,而不是视图。有什么办法这个逻辑移到型号?感谢您的任何想法/见解。

But I am responding to a business rule and I really think it should be in the Model, not the View. Is there any way to move this logic to the Model? Thanks for any ideas/insights.

推荐答案

请它的返回值是由其他属性决定模型的只读属性:

Make it a read-only property of your model whose return value is decided by the other properties:

请注意:你的code后续的假设。因为你需要重新蹦蹦这:

Note: Assumptions about your code follow. Re-jig this as you need to:

public class YourModel {
    public string FuelType { get; set; }
    public int VehicleYear { get; set; }

    public string CatalystLabelText {
        get {
            return (this.FuelType == "D" &&
                   this.VehicleYear >= 2009) ? _resNMHCCatalyst : _resCatalyst;
        }
    }
}

您认为然后(正确地)变成了看法..而不是决策者:

Your view then (correctly) becomes a view.. and not a decision maker:

<b> @Html.LabelFor(model => model.testObd.Catalyst, Model.CatalystLabelText) </b>

这篇关于在MVC EF显示名称两个标签之间进行动态选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆