Learner
Learner

Reputation: 351

How to return a specified Json format in c#

Hi all I am trying to build a quiz application using angular JS, I am having two tables Questions and Answers and the code is as follows

public class Question
{
    public int QuestionID { get; set; }
    public string QuestionName { get; set; }
    public List<Options> Options = new List<Options>();
}

public class Options
{
    public int AnswerId { get; set; }
    public int QuestionID { get; set; }
    public string Answer { get; set; }
    public bool isAnswer { get; set; }
}

public static class QuizDetails
{
    public static string GetQuiz()
    {
        Dictionary<int, List<Question>> displayQuestion = new Dictionary<int, List<Question>>();

        //List<Quiz> quiz = new List<Quiz>();
        //Options op1 = new Options();

        dbDataContext db = new dbDataContext();
        var v = (from op in db.QUESTIONs
                 join pg in db.ANSWERs on op.QUESTION_ID equals pg.QUESTION_ID
                 select new { Id = op.QUESTION_ID, Name = op.QUESTION_NAME, pg.ANSWER_ID, pg.QUESTION_ID, pg.ANSWER_DESCRIPTION, pg.CORRECT_ANSWER }).ToList();
        return JsonConvert.SerializeObject(v);
    }
}

This is my reference code for building the application http://www.codeproject.com/Articles/860024/Quiz-Application-in-AngularJs, how can I return the JSON format as per the code written in the JS files can some one help me

Upvotes: 0

Views: 82

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

Right now GetQuiz returns a string that represents an object. Your client doesn't really know what the string contains, it just handles it as a normal string.

You can either return it in another way, for example:

return new HttpResponseMessage
            {
                Content = new StringContent(
                    JsonConvert.SerializeObject(v),
                    System.Text.Encoding.UTF8,
                    "application/json")
            };

If you want to keep returning it as a string you will have to manually deserialize it in the client:

var object = angular.fromJson(returnedData);

Upvotes: 1

Related Questions