esamaldin elzain
esamaldin elzain

Reputation: 358

How to use variables in Asp .NET Core MVC within cshtml view?

I am migrating from .Net Framework to .Net 5.0, and I am trying to use variables inside Razor views like normal asp MVC, there is a syntax error in the @page variable

Error: The '@page' directive must precede all other elements defined in a Razor file.

Error: The 'page` directive must appear at the start of the line.

Error: The 'page' directives value(s) must be separated by whitespace.

code:

@for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
 {
       if (page == Model.Pager.CurrentPage)
       {
         <li class="active"><span style="line-height:20px">@page</span> </li>
       }
       else
       {
        <li><a href="@Url.Action("Index","Blogs",new { page = @page,pageSize=10 })">@page</a></li>
       }
  }

Upvotes: 3

Views: 6207

Answers (2)

Adeel Ahmed
Adeel Ahmed

Reputation: 345

Use simple page or @(page) instead of @page, errors will be resolved.

Upvotes: 5

Serge
Serge

Reputation: 43870

For razor pages @page is a reserved word that should be in the first line. You should never use it for the custom code:

So rewrite your code like this:

@page

..... your html

@for (var pg = Model.Pager.StartPage; pg <= Model.Pager.EndPage; pg++)
 {
       if (pg == Model.Pager.CurrentPage)
       {
         <li class="active"><span style="line-height:20px">@pg</span> </li>
       }
       else
       {
        <li><a href="@Url.Action("Index","Blogs",new { pg = @pg , pageSize=10 })">@pg</a></li>
       }
  }

Upvotes: 2

Related Questions