user2630764
user2630764

Reputation: 622

Using If statement in a MVC Razor View

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

Upvotes: 9

Views: 64960

Answers (3)

Brian Maupin
Brian Maupin

Reputation: 745

I would try this:

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

Upvotes: 2

hunter
hunter

Reputation: 63562

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

Try this instead:

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

Upvotes: 13

Andrey Gubal
Andrey Gubal

Reputation: 3479

You do not need to use @{} inside @if. Write like this:

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

Upvotes: 0

Related Questions