user659469
user659469

Reputation: 325

string comparison with MVC razor view

I am trying to compare strings using following but it doesn't go inside the if loop

@if (Convert.ToString(ViewData["value"]) == "Exit")
{  
    <div style="width:100%; border-top:1px solid #999999; padding-top:10px;"> 
    </div>
}
else if (Convert.ToString(ViewData["value"]) == "SessionTimedOut")
{
    <div style="width:100%; border-top:1px solid #999999; padding-top:10px;"> 
    </div>
}

Upvotes: 0

Views: 11798

Answers (1)

Rion Williams
Rion Williams

Reputation: 76547

Ensure Your Values Are Correct

You might consider checking to make sure that your ViewData["value"] actually contains what you expect. Are you settings this within the Controller?

Try adding a breakpoint within your View and examining what this looks like either a statement like the following or your Watch window :

@{ 
       // Place a breakpoint here
       var section = Convert.ToString(ViewData["value"]);
}

Check your Context

If you are already in the context of a loop, you shouldn't need to preface your if-statement with a @ character.

@foreach(var foo in bar){
    // Notice that no leading @ is required here 
    if(...){

    }
    else if (...){

    }
}

Explicitly Separate Through <text> Tags

If you aren't in the context and explicitly wanted to discern markup from your code, you could use the <text> tags :

@if (Convert.ToString(ViewData["value"]) == "Exit")
{  
   <text>
       <div style="width:100%; border-top:1px solid #999999; padding-top:10px;">
          <!-- Your Code Here -->
       </div>
   </text>
}

Combining Statements

Additionally, both of your statements appear to currently output the same code. You could consider merging these into a single statement using :

@if (new[]{ "Exit", "SessionTimedOut"}.Contains(Convert.ToString(ViewData["value"])){  
    <div style="width:100%; border-top:1px solid #999999; padding-top:10px;">
        <!-- Your code here -->
    </div>
}

Otherwise, you could consider using a switch statement to more cleanly separate your query :

@switch(Convert.ToString(ViewData["value"])){
     case "Exit":
          <!-- Your Markup for Exit Here -->
     break;
     case "SessionTimedOut":
          <!-- Your Markup for SessionTimedOut Here -->
     break;
}

Upvotes: 3

Related Questions