Share via


if else nested within a foreach

Question

Friday, May 2, 2014 9:59 AM

Hi,

I'm just starting out with ASP.NET Web Pages having been developing in Classic ASP for the past 11 years (I know, long overdue :-))

For a test project I'm converting a simple Classic ASP CMS site to ASP.NET Web Pages using Webmatrix.

I need to create a "foreach" loop to create a primary menu/navigation drawn from a MySQL database - which I've done and it all works fine. However I now need to add some conditional logic within the loop and I'm having problems and getting this compliation error:

**Compiler Error Message: **CS1513: } expected

Here is my code:

<div id="menuprimary">
  <ul>     
    @foreach(var row in db.Query(primarymenu)){

    menupgId = @row.pgId;
    menutitle = @row.pgMenuTitle;
    menulinktitle = @row.pgLinkName;
 
    if(Convert.ToInt32(Request.QueryString["pgId"]) == menupgId) {
    activeclass = " style=\"color:#6d6d6d;\""; 
    }
    else {
    activeclass = "";
      }
 
    if(menupgId) == 1 {
      lnkstr = siteurl;
      }
    else {
      lnkstr = siteurl + (menupgId) + "/" + (menulinktitle) + "/";
      }
 
        
    <li><a href="@lnkstr"@Html.Raw(activeclass)>@menutitle</a></li>
    }       
  </ul>
</div>

The loop gets the rows from the database (earlier in the code) and on each loop assigns the values to various variables (that bit is all ok). Then there is a bit of conditional logic that checks whether the querystring "pgId" value is the same this iteration/loop value for pgId (menupgId) - if it is then it writes a values (some style code) to a variable "activeclass" - this is then used later when creating the html navigation so that the "active" page menu/navigaiton link is styled/coloured different to the other links.

Then there is another if/else statement to check whether this is the "home" page of the site (pgId = 1) or another (internal) page - if it is the home page (menupgId = 1) then the url for this link will just be the "siteurl" (variable set earlier on in the code which is the site url/domain name) - if it is any other page the variable lnkstr is constructed making up a SEO friendly URL - siteurl + menupgId + / + menutitle + / + (i.e. http://www.mydomain.com/2/contact-us/)

If I run the page without the if/else statements it works - if I run it with the if/else statements I get the error about } expected.

I've tried various searches but each answer dealt with writing blocks of html within each if/else whereas I want to assign a value to a variable in each statement so the solutions I've found don't seem to work for me.

I'm stumped, can anyone help me please?

Regards
AP

All replies (4)

Friday, May 2, 2014 10:08 AM âś…Answered

scimitar

<div id="menuprimary">
    <ul>
        @foreach(var row in db.Query(primarymenu)) {
        menupgId = @row.pgId;
        menutitle = @row.pgMenuTitle;
        menulinktitle = @row.pgLinkName;

            if(Convert.ToInt32(Request.QueryString["pgId"]) == menupgId) {
                activeclass = " style=\"color:#6d6d6d;\"";
            }
            else {
                activeclass = "";
            }

            if(menupgId) == 1 {
                lnkstr = siteurl;
            }
            else {
                lnkstr = siteurl + (menupgId) + "/" + (menulinktitle) + "/";
            }

            <li><a href="@lnkstr" @Html.Raw(activeclass)>@menutitle</a></li>
        }
    </ul>
</div>

I reformatted your code a bit to make it easier to verify that all your braces were closed.  The issue is that you have unnecessary @ symbols here, which are preventing the compiler from parsing your file correctly:

menupgId = @row.pgId;
menutitle = @row.pgMenuTitle;
menulinktitle = @row.pgLinkName;

If you're assigning things into C# variables, you're already inside Razor syntax, and don't need to use the @ symbol.

If you're using Visual Studio (Definitely 2013 Express for Web, probably most versions since 2012 at least), any @ that distinguishes Razor C# from HTML gets highlighted in yellow by the editor, so it makes it pretty obvious if it's having the intended effect.

EDIT: You're going to have another problem with one of your if statements once you fix that:

if(menupgId) == 1

Should be

if(menupgId == 1)

Friday, May 2, 2014 10:19 AM

Hi,

Thanks for the speedy reply.

I removed the @ symbol from the row. for the looping variables, like this:

menupgId = row.pgId;
menutitle = row.pgMenuTitle;
menulinktitle = row.pgLinkName;

But I still get a compliation error like this:

Server Error in '/' Application.


Parser Error

**Description: **An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. 

**Parser Error Message: **Expected a "{" but found a "==".  Block statements must be enclosed in "{" and "}".  You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed:

@if(isLoggedIn)
   <p>Hello, @user\</p>

Instead, wrap the contents of the block in "{}":

@if(isLoggedIn) {
   <p>Hello, @user\</p>
}

Source Error: 

Line 89:       }
Line 90: 
Line 91:     if(menupgId) == 1 {
Line 92:       lnkstr = siteurl;
Line 93:       }

**Source File: /index.cshtml    Line: **91 

Not sure what to do now.

Thanks again.

AP


Friday, May 2, 2014 10:26 AM

Looks like you were replying as I was editing my first post to cover this.  Conditions for if statements must be completely enclosed in parentheses - see my edit.


Friday, May 2, 2014 10:52 AM

ahhh,

thanks for that - parentheses now enclosing the condition and all is working.

Many thanks for your speedy help.