dynamically choose between two labels for the Display Name in mvc ef
asp.net-mvc, asp.net-mvc-4, c#, entity-framework
Solution
Make it a read-only property of your model whose return value is decided by the other properties:
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>
Problem
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)); } } ``` 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.