Home > OS >  Show a word as out for the number input
Show a word as out for the number input

Time:09-26

I have a model class, in that for an object named "Action" will be have input from 1 to 5.
if the input is 1 I need to show as Leave Certificate
eg: In the view it will shown as Leave Certificate, but in database the value for that will be stored as 1.

I don't know how to do it in ASP Net core, I don't have any clue, how should the code for it so and so.

I tried to use if else statement but I couldn't. And I tried it with Enum ,then also it leads to an error.

CodePudding user response:

One solution would be to add a calculated property in your model that returns a string based on the value of the Action property. The Action property will have the value stored in the database and the ActionDisplayValue will be used in your views.

Example:

public class MyModel
{
    public int Action { get; set; }

    public string ActionDisplayValue => Action switch
    {
        1 => "Leave Certificate",
        2 => "aaa",
        3 => "bbb",
        4 => "ccc",
        5 => "ddd",
        _ => throw new InvalidOperationException($"Unsupported Action {Action}.")
    };
}

CodePudding user response:

I suggest save enum as string instead int in your database and use in view, but if you don't want, you can use this way:

Use Enum for actions and numbers.

ActionEnum.cs :

public enum ActionEnum
{
  LeaveCertificate = 1,

  SomeAction = 2,

  AnotherAction = 3
}

In future if you want to add another name or description to enum members you can use [Discplay(name="",description="")] above enum members.

And your ExampleModel.cs:

public class ExampleModel
{
    public int Action { get; set; }

    public string GetActionName()
    {
       var enumMember = (int)ActionEnum;
       return enumMember.ToString();
    }
}
  • Related