1

My model has property

public enum CheckStatus { A = 1, B = 2, C = 3, } public CheckStatus Status { get; set; } 

and inside razor view I want to switch this property like

@switch (Model.Status) { case 1: default: <div>Selected A</div> break; case 2: <div>Selected B</div> break; case 3: <div>Selected C</div> break; } 

Cannot implicitly convert type 'int' to 'CheckStatus'. An explicit conversion exists (are you missing a cast?)

9
  • 2
    You ought to do like case A: Commented Feb 25, 2014 at 13:00
  • And your question is? Commented Feb 25, 2014 at 13:01
  • @decPL my question is: how many eggs do I need to bake perfect omlet ? I think it's obvious from error I provide. Commented Feb 25, 2014 at 13:02
  • 2
    @user1765862 and why don't you have the enum values for your switch cases? You don't need/care about the int value for this. Commented Feb 25, 2014 at 13:04
  • @user1765862 The answer is obvious too, and included in the error message itself. Do an explicit cast ie (int)Model.Status. But why don't you use the Enum values? Commented Feb 25, 2014 at 13:04

2 Answers 2

5

Your switch statement parameter and the case Label must be of the same datatype.

so cast your enum to int like this

switch ((int)Model.Status) { case 2: <div>Selected B</div> break; case 3: <div>Selected C</div> break; default: <div>Selected A</div> break; } 

or use the CheckStatus in your case statement as well

switch (Model.Status) { case CheckStatus.B: <div>Selected B</div> break; case CheckStatus.C: <div>Selected C</div> break; default: <div>Selected A</div> break; } 

I removed the first case as you are not doing anything in that case. Also put the default case at the end which make things readable. You can also use the Case 1 and remove the default (if you want)

Sign up to request clarification or add additional context in comments.

Comments

0

try this

switch((int) Model.Status) { } 

to reach your goal!

Appendix: Model.Status would just return A, B etc, not the integer values behind.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.