Creating a JSON result from SQL server database

前端 未结 2 1084
梦谈多话
梦谈多话 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

提交回复
热议问题