Reputation: 2569
What's the suggested way of converting values between a controller and a view if they don't match each other?
// Basic model with enum property
public class MyModel {
public State MyState { get; set; }
}
// Enum denoting 3 states
public enum State {
Ready,
Set,
Go
}
// API/MVC/Module/SignalR controller
public class MyController : MiddlewareController {
public MyController() {
Get = _ => {
return View["myView", new MyModel()];
};
}
}
// myView
<div class="@Model.State"></div>
Now, the string representations of the enum values are "Ready", "Set" and "Go", but in my view, I need ".red", ".yellow", ".green".
Of course, in my controller, I could make a function that returns the appropriate CSS value, but that feels just wrong because I'm leaking view-concerns into my controller. Is there something like a value-converter?
Upvotes: 0
Views: 110
Reputation: 3061
if you cannot use the css as I suggested I think key-value dictionary is the way to go. Especially this is a site wide issue.
public static Dictionary<State, string> StatusClassName = new Dictionary<State, string>();
StatusClassName.Add(State.Ready, "red");
...
after that you can use what ever way you want like;
StatusClassName[Model.State]
or you can write an extension method to use like
Model.State.GetClassName();
Upvotes: 1
Reputation: 3787
You can convert it in view:
@{
string className = string.Empty;
switch (Model.State)
{
case State.Ready:className = "red"; break;
case State.Set:className = "green"; break;
case State.Go: className = "yellow"; break;
}
}
<div class="@className"></div>
Upvotes: 0