Creating a JSON result from SQL server database

前端 未结 2 1078
梦谈多话
梦谈多话 2020-12-19 15:26

I have an SQL server with the following layout

Table (    id int
           title varchar(40),
           start Date(),
           end Date(),
           al         


        
相关标签:
2条回答
  • 2020-12-19 15:43

    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

    0 讨论(0)
  • 2020-12-19 16:08
    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

    0 讨论(0)
提交回复
热议问题