Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - 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,
           username varchar(40)
      );

I have gotten the following code from this blog to create a JSON object from the data I wish to use, however his data is stored differently. How do I create the same object, extracted from my database?

I am guessing I need to make the file a .cshtml file rather than a .js file and use this :

@{
    var db = Database.Open("events"); 
    var selectQueryString = "SELECT * FROM events";
}

 @foreach(var row in db.Query(selectQueryString)){ }

But how do I adapt this code to produce the same JSON object?

Here is the relevant code from the blog, my attempt is below :

public JsonResult GetEvents(double start, double end)
{
    var userName = Session["UserName"] as string;
    if(string.IsNullOrEmpty(userName))
    {
        return null;
    }

    var fromDate = ConvertFromUnixTimestamp(start);
    var toDate = ConvertFromUnixTimestamp(end);


    var rep = Resolver.Resolve<IEventRepository>();
    var events = rep.ListEventsForUser(userName,fromDate,toDate);

    var eventList = from e in events
                    select new {
                                id = e.Id,
                                title = e.Title,
                                start = e.FromDate.ToString("s"),
                                end = e.ToDate.ToString("s"),
                                allDay = false
                            }; 

    var rows = eventList.ToArray();
    return Json(rows,JsonRequestBehavior.AllowGet);           
}

Edit :

I am now working with the following .cshtml code for the GetEvents command, but it will not work. Does anybody have any ideas ?

   @{ 
        var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        var fromDate = origin.AddSeconds((Request["start"]));
        var toDate = origin.AddSeconds(Request["end"]);

        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";
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...