Search code examples
databasejsonlinqlinq-to-sqlashx

LINQ to SQL how to use it in .ashx file to generate json?


I have some problem to Figure out how to use LINQ to SQL in .ashx file to generate json? I am able to generate json using this code but I need to select TaskName and createdOn columns. can someone help me how to select TaskName and createdOn columns to generate json?

        //DataClasses1DataContext db = new DataClasses1DataContext();
        //var tasksCreatedOm = from c in db.Tasks
        //                     select c.createdOn;

        //the bloack will get all data in table 
        context.Response.ContentType = "text/json";
        context.Response.Write(new SchedulerAjaxData(new  DataClasses1DataContext().Tasks));

My Tasks Class enter image description here


Solution

  • Try something like the following (untested):

    using(DataClasses1DataContext db = new DataClasses1DataContext())
    {
        var tasksCreatedOn = from c in db.Tasks
                            select new { c.taskName, c.createdOn };
    
        // This block will get all data in table 
        var serializer = new JavaScriptSerializer();
        context.Response.ContentType = "text/json";
        context.Response.Write(serializer.Serialize(tasksCreatedOn));
    }
    

    First I projected your Tasks into an anonymous type containing taskName and createdOn. Then I used the JavaScriptSerializer to serialize them to JSON. I also added a using block so that the DataContext is disposed of properly.