Developer forum

Forum » CMS - Standard features » Read SQL database directly from Razor templates

Read SQL database directly from Razor templates

Hans Ravnsfjall
Hans Ravnsfjall
Reply

Hi

in a cshtml pagetemplate, is it possible to output values from a custom SQL database table directly? If so, is it also possible on a Dynamicweb 8 solution and how can it be done?

I want to output the tabledata as JSON data

/Hans


Replies

 
Nicolai Pedersen
Reply
This post has been marked as an answer

Yes. It is just regular C# code:

Here I use Dynamicweb.Data to get hold of the datatable:

@{ 
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        System.Data.DataTable dt = Dynamicweb.Data.Database.CreateDataTable("SELECT * FROM PAGE");
        foreach (System.Data.DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (System.Data.DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        @serializer.Serialize(rows)
    }
Votes for this answer: 1
 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

Perfect, thank you Nicolai 👍🏻

/Hans

 

You must be logged in to post in the forum