1

I have some ASP.NET code to fetch from my database. The code is as follows:

@{ //begin block

var appDb = Database.Open("apps");
var msg = "hi";
Layout = "~/Header.cshtml";
var queryStr = "SELECT * FROM Apps WHERE appid = '" + @Request.QueryString["id"] + "'";
foreach (var query in appDb.Query(queryStr)) { //begin foreach
    <img src="@query.pictureUrl" /><br>
    <h2 style="display:  inline;"></h2> <h3 style="display: inline;">by </h3>
   <p>

       </p>
} // end foreach
} // end block

However, WebMatrix says that the //end foreach is the end of the block, not the end of the foreach. It also comes up with this error:

"}" expected at line 
<end of file, i'm only copying the errored block but for me it's line 19>
 at column 4

So I fix the error, and guess what? It comes up AGAIN. Fix again, appear again and so on.

How do I fix the error

3
  • 2
    A little bit off topic, but you should find some information about Sql Injection
    – Rudis
    Commented Oct 12, 2013 at 20:03
  • Comment out stuff to narrow down the possible causes.
    – usr
    Commented Oct 12, 2013 at 20:06
  • @Rudis SQL Injection is never off topic. Just think about all those Little Bobby Tables out there!
    – Uwe Keim
    Commented Oct 12, 2013 at 20:36

1 Answer 1

0

Razor is fussy about open HTML tags being matched with closing ones. The error message is not always that helpful, but your issue is cause by the <br>tag not being closed. All you need to do is add a '/' to it:

@{ 
var appDb = Database.Open("apps");
var msg = "hi";
Layout = "~/Header.cshtml";
var queryStr = "SELECT * FROM Apps WHERE appid = @0";
foreach (var query in appDb.Query(queryStr, Request.QueryString["id"])) { 
    <img src="@query.pictureUrl" /><br />
    <h2 style="display:  inline;"></h2> 
    <h3 style="display: inline;">by </h3>

    <p></p>
    } 
}

I have also addressed the rightful concern from Rudis about SQL Injection and replaced your string concatenation with a parameter. Incidentally, if you only expect to get one row of data as a result of your query, you should use QuerySingle instead of Query:

@{ 
    var appDb = Database.Open("apps");
    var msg = "hi";
    Layout = "~/Header.cshtml";
    var queryStr = "SELECT * FROM Apps WHERE appid = @0";
    var record = appDb.QuerySingle(queryStr, Request.QueryString["id"]); 
    if(record != null){
        <img src="@record.pictureUrl" /><br />
        <h2 style="display:  inline;"></h2> 
        <h3 style="display: inline;">by </h3>

        <p></p>
    } 
}

You can learn a lot more about managing data within Web Pages here: http://www.asp.net/web-pages/tutorials/data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.