Link to home
Start Free TrialLog in
Avatar of CEL_IT
CEL_IT

asked on

how to pass database results from a class in asp.net web pages

Hello,

I can run sql doing the following on a page:

var db = Database.Open("DefaultConnection");
var selectBrands = db.Query("SELECT DISTINCT SubDescription1 AS Brands FROM dbo.Item");
db.Close();
@foreach (var row in selectBrands )
{
<li>row.Brands</li>
}

What I want to do is run the sql query within a function in a class. The function will return the data which I am trying to iterate through. I have attached text file with the code.

I get the following error:

Error      19      'object' does not contain a definition for 'Brands' and no extension method 'Brands' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

What I am trying to do is separate markup from logic by setting up classes, is this the right way of going about it?
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Are you using ASP.NET MVC? The "@" in your view makes it look like you're using Razor syntax.

If using MVC you should retrieve the data in your Controller and then pass it to the View as a strongly-typed Model.

There is no attached file.
Avatar of CEL_IT
CEL_IT

ASKER

Sorry about the attachement, I am not using MVC but Web Page Razor V3.
test.txt
ASKER CERTIFIED SOLUTION
Avatar of Craig Wagner
Craig Wagner
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just wondering isn't using WebPages means there isn't any code-behind but you do inline coding?
Avatar of CEL_IT

ASKER

Craig,

that's worked perfect! thank you for the explanations as well. Do we need to close the database connection inside the using as below?

public class Menus
{
    public IEnumerable<dynamic> getBrands()
    {
        using( var db = Database.Open("DefaultConnection") )
        {
            var selectBrands = db.Query("SELECT DISTINCT SubDescription1 AS Brands FROM dbo.Item");

            db.Close();
            return selectBrands;
    }
}

Open in new window

No, you don't need to close the database connection. When you exit the "using" block the connection will be closed and disposed automatically.
Avatar of CEL_IT

ASKER

thank you so much craig : )