Using If statement in a MVC Razor View

63,660

Solution 1

grid isn't declared outside of the scope of your if statment.

Try this instead:

@if (Model.SModel != null) {
    WebGrid(Model.SModel).GetHtml()
}

Solution 2

I would try this:

@if (Model.SModel != null)
{
    WebGrid grid = new WebGrid(Model.SModel);
    grid.GetHtml()
}
else
{
}
Share:
63,660
user2630764
Author by

user2630764

Updated on August 15, 2022

Comments

  • user2630764
    user2630764 over 1 year

    In the following code,

    If I use "@If" statement ,I get the following compile code error as " The name 'grid' does not exist in the current context.

    @if (Model.SModel != null)
    
    {
    
    @{ 
        WebGrid grid = new WebGrid(Model.SModel);
    
     }
    
     }
    
     else
     {
    }
    
    @grid.GetHtml()
    

    ,

    But the code compiles without the "If" statement.For example

    @{ 
        WebGrid grid = new WebGrid(Model.SModel);
    
    }
    @grid.GetHtml().
    

    What is the syntactical error in using If else statement

  • hunter
    hunter over 10 years
    grid doesn't exist outside of the if statement
  • hunter
    hunter over 10 years
    grid won't exist outside of the if statement