Creating A JSON Result From SQL Server Database
I have an SQL server with the following layout Table ( id int title varchar(40), start Date(), end Date(), allDay bool, u
Solution 1:
There are no controllers and actions in WebMatrix WebPages. You need to write a separate .cshtml
page that will query the database and serve the JSON to the response:
@{
var db = Database.Open("events");
var result = db.Query("SELECT * FROM events");
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
and then in another page in which you want to display the calendar you could configure it:
$(document).ready(function() {
$('#calendar').fullCalendar({
theme: true,
header: {
left: '',
center: '',
right: ''
},
defaultView: 'agendaDay',
editable: false,
events: '/events.cshtml'
});
});
UPDATE: Here's an example of how you could use parametrized queries:
@{
var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
var fromDate = origin.AddSeconds(int.Parse(Request["start"]));
var toDate = origin.AddSeconds(int.Parse(Request["end"]));
var db = Database.Open("events");
var sql = "SELECT * FROM events WHERE start >= @0 AND end <= @1";
var result = db.Query(sql, fromDate, toDate);
var data = result.Select(x => new
{
id = x.id,
title = x.title,
start = x.start.ToString("s"),
end = x.end.ToString("s"),
allDay = false
}).ToArray();
Json.Write(data, Response.Output);
Response.ContentType = "application/json";
}
Now you could query the page like this: /events.cshtml?start=5&end=10
Solution 2:
DECLARE @listCol VARCHAR(2000)
DECLARE @query VARCHAR(4000)
SELECT @listCol = STUFF(( SELECT distinct '], [' + [PSize]
FROM Pattern
FOR
XML PATH('')
), 1, 2, '') + ']'
SET @query = 'SELECT * FROM
(SELECT PColour as Colour_Size_Matrix, PSize, PCode
FROM Pattern
) src
PIVOT (Count(PCode) FOR PSize
IN (' + @listCol + ')) AS pvt'
EXECUTE ( @query )
I want the result of this query as JSON
Post a Comment for "Creating A JSON Result From SQL Server Database"