0

i have below method:

    [HttpPost]
    public ActionResult GetData()
    {
        var data= (dynamic)null;
        using (DBContext context = new DBContext())
        {
            data= context.MyObject.Where(i=> i.TypeId == 1).OrderBy(k => k.Name).Select(w => new
            {
                description = w.Description
            }).ToList();       
        }

        return Json(data, JsonRequestBehavior.AllowGet);
    }

so I want to convert the data correctly into a json object, but i am not sure if i am doing correctly. This data returned should be used in a javascript.

I have google a lot and i have found example like below, maybe I should do a similar thing, but i do not know how:

var keyValues = new Dictionary<string, string>
               {
                   { "emailSend", textBox1.Text },
                   { "toEmail", textBox2.Text }
               };

JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
MessageBox.Show(json);
7
  • Use Newtonsoft.Json! Commented Sep 23, 2013 at 11:16
  • 2
    Your code will return Json? your calling Json() in your controller. This will convert your object into Json. No need for anything else. Commented Sep 23, 2013 at 11:17
  • I should be return json data but i am not sure if i am done it correctly from the controller. Commented Sep 23, 2013 at 11:19
  • MessageBox.Show is a windows method and won't work in ASP.Net also Commented Sep 23, 2013 at 11:19
  • 2
    return Json(data, JsonRequestBehavior.AllowGet); is the correct way Commented Sep 23, 2013 at 11:19

1 Answer 1

7

You should not be using any JavaScriptSerializer. Just return Json as you already did. That's the correct approach of sending JSON to the client from a controller action. The model you passed as parameter will automatically be serialized into a JSON string by the framework. Also you don't need to be setting JsonRequestBehavior.AllowGet because your controller action is decorated with the [HttpPost] attribute meaning that it can only be invoked with the POST verb and never with GET. This is required only for controller actions that are returning JsonResult and which can be invoked with the GET verb.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.