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>}
}
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>}
}
Hello, i dont understand this: the connection string must be in the Web config file,,, thank you
ReplyDeleteThanks for the always useful information. This is great information to help garage type SEO people like me.RazorSQL 7.3.2
ReplyDelete