简体   繁体   中英

Converting c# data from entity framework to a valid json type

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM