3

I have developed a simple WebAPI 2 application which include this get method:

    public HttpResponseMessage Get(int id)
    {
        var x = db.TESTS.ToList();
        var formatter = new JsonMediaTypeFormatter();
        return Request.CreateResponse(HttpStatusCode.OK, x, formatter);
    }

I checked. It is returning Json value. I also checked it in Fiddler.

But when I want to retrieve this in a simple html file, I am getting parse error. My Web Service is published in localhost.

Web service url: http://192.168.5.154/mobileapi/api/values/2 is returning

[{"ID":2.0,"TEXT":"test 2"},{"ID":1.0,"TEXT":"test"}]

Here's the code.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Get Json value from WebAPI url</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            jQuery.ajax({
                type: "GET",
                url: "http://192.168.5.154/mobileapi/api/values/2?callback=?",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, status, jqXHR) {
                    alert("data is available");
                },

                error: function (jqXHR, status) {
                    alert(status);
                }
            });

        });

    </script>

</body>
</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Syed Md. Kamruzzaman
  • 979
  • 1
  • 12
  • 33

2 Answers2

1

Update your Controller code:

  using System.Web.Script.Serialization;



  [HttpGet]
        public JsonResult  Get(int id)
        {
            var ListOfMyObject = db.TESTS.ToList(); 
            JavaScriptSerializer jss = new JavaScriptSerializer();

            string output = jss.Serialize(ListOfMyObject);
            return Json(output , JsonRequestBehavior.AllowGet);  
        }

Read up from here. Why is JsonRequestBehavior needed?

Community
  • 1
  • 1
Muks
  • 134
  • 9
  • this is showing error: Error 1 The best overloaded method match for 'System.Web.Http.ApiController.Json(System.Net.Http.Formatting.JsonMediaTypeFormatter, Newtonsoft.Json.JsonSerializerSettings)' has some invalid arguments – Syed Md. Kamruzzaman Aug 18 '15 at 10:19
  • Is the variable x ever returned? – Ebsan Aug 18 '15 at 10:21
  • Okay, Try the code, I am now returning the x instead of a formatter. – Muks Aug 18 '15 at 10:27
  • ok, now showing this error: Error 1 The best overloaded method match for 'System.Web.Http.ApiController.Json(string, Newtonsoft.Json.JsonSerializerSettings)' has some invalid arguments – Syed Md. Kamruzzaman Aug 18 '15 at 10:32
  • another error: Error 2 Argument 2: cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings' – Syed Md. Kamruzzaman Aug 18 '15 at 10:40
0

Alhamdulillah, this is solved.

needed to enable CORS on web service.

Steps. 1. Install Microsoft ASP.NET Web API 2.2... 5.2.3 from Nuget Packages 2. Add config.EnableCors(new EnableCorsAttribute("*", "*", "*")); in WebApiConfig

My Json Code in html is:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Get Json value from WebAPI url</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>


    <script type="text/javascript">
            var getJSON = function (url) {
                return new Promise(function (resolve, reject) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('get', url, true);
                    xhr.responseType = 'json';
                    xhr.onload = function () {
                        var status = xhr.status;
                        if (status == 200) {
                            resolve(xhr.response);
                        } else {
                            reject(status);
                        }
                    };
                    xhr.send();
                });
            };

            getJSON('http://192.168.5.154/mobileapi/api/values/2').then(function (data) {
                //alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug
                //alert(data.TEXT);

                result.innerText ="Oracle Data\nId: " + data.ID + "\nText: "+  data.TEXT; //display the result in an HTML element
            }, function (status) { //error detection....
                alert('Something went wrong.');
            });

    </script>

    <div id="result" style="color:red"></div>

</body>
</html>

My web service code is:

   public IHttpActionResult Get(int id)
        {
            var product = db.TESTS.FirstOrDefault((p) => p.ID == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);         
        }
Syed Md. Kamruzzaman
  • 979
  • 1
  • 12
  • 33