Umbraco Razor, How to Connect and Query to a SQL Database and Loop around the Results, and use a Helper to display the results

1. Connect to the Database (the connection string must be in the Web config file)
2. Loop around the results (this code loops around a database that stores vistits to FAQ pages, and stores the Page ID)
3. Use a helper to display the results

KEY:
Field names in Database 


@inherits umbraco.MacroEngines.DynamicNodeContext
@using WebMatrix.Data


@{
// 1 Contect to the Database and Select the items
        var DB = Database.Open("myAnalyticsConnection");
var FAQs = DB.Query("SELECT * FROM Analytics WHERE docType='FAQ'  ORDER BY numberOfClicks DESC").Take(5);

}


@{
// 2For Each of the Items(FAQs) loop arround
foreach (var FAQ in FAQs)
{
@getPageLink(FAQ.pageId)
}
}




@helper getPageLink(int thisPage)
{
//3.  A Helper to get the node URL, as this is not stored in the database
try {

var thisPageId = @Model.NodeById(@thisPage);

<li style="text-align:left;background-image: url(/images/arrow-white.png);">
<a href="@thisPageId.Url">
<span style="color:#ffffff">@thisPageId.Name</span>
</a>
</li>

}
catch{<text>error</text>}

}

Comments

  1. Hello, i dont understand this: the connection string must be in the Web config file,,, thank you

    ReplyDelete
  2. Thanks for the always useful information. This is great information to help garage type SEO people like me.RazorSQL 7.3.2

    ReplyDelete

Post a Comment

Popular posts from this blog

Umbraco - Reset the Admin Password via SQL Server

Create a .NET Contact Form that Gets the Last Url Visited in C# Can also be Used in Umbraco

Umbraco Macro for IFrame when Embedding Video, Vimeo Universal Player, or other types of IFrame on to a Page XSLT version and Razor Version