Using If statement in a MVC Razor View

筅森魡賤 提交于 2019-12-09 09:31:55

问题


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


回答1:


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

Try this instead:

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



回答2:


I would try this:

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



回答3:


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

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


来源:https://stackoverflow.com/questions/18062882/using-if-statement-in-a-mvc-razor-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!