简体   繁体   中英

How to get MVC Controller json data in JavaScript using ajax

I am using .NET C# MVC/API project. Inside a Controller I have the following code:

    [HttpGet]
    public ActionResult ArcGISinit()
    {
        var jsonString = "[{ 'number': '555', 'api': '777', 'text': 'text'}]";
        return Json(jsonString, JsonRequestBehavior.AllowGet);
    }

Then in my script file, I am able to get the above data like this:

        // Path to the above **Controller**
        var serviceURL = "...";

        var respOriginal = [{ "number": 555, "api": "777", "text": text }]; 

        $.ajax({
            type:        "GET",
            url:         serviceURL,
            contentType: "application/json;",
            dataType:    "json",
            success:     successFunc,
            error:       errorFunc
        });

        function successFunc(data, status) {

            // Probably don't need this
            resp = JSON.stringify(data); 

            console.log("data:");
            console.log(data);
            console.log("respOriginal:");
            console.log(respOriginal);
        }

        function errorFunc() {
            alert('MVC controller call failed.');
        }

Here is a thing when I look at it Chrome debugger, in data which is from MVC Controller I get this (a plain string):

[{ 'number': '555', 'api': '777', 'text': 'text'}]

but for respOriginal which is inside a script file, I get this

[Object]

When Object is expanded (data in respOriginal ) looks properly formatted, like so:

number : 555
api : 777
text : "text"

How can I make data that comes from MVC Controller look like data in respOriginal ?

I would suggest creating WebAPI controller for API functions, it is more flexible out of the box and made just. Also you are separating your API from your views, and can have 401 or error handling just by changing the HttpStatusCode parm

[HttpGet]
public async Task<HttpResponseMessage> ArcGISinit()
{
    var yourObjectArray = new object[] { new { number = 555, api = 777, text = "text" } };
    return Request.CreateResponse(HttpStatusCode.OK, yourObjectArray);
}

And for the JS you are right you don't need stringfy (that is when you want to cast JS object to JSON formated string), just use the variable like data.number

Make an anonymous object or pass in any instance of a class resembling your structure ... you got square brackets around the object so i guess it's an array:

[HttpGet]
public ActionResult ArcGISinit()
{
    object[] yourObjectArray = new object[]{ new { number = 555, api = 777, text = "text"} };
    return Json(yourObjectArray , JsonRequestBehavior.AllowGet);
}

A proper class would look like:

public class YourClass
{
    public int number {get;set;}
    public int api {get;set;}
    public string text {get;set;}
}

And on the controller:

[HttpGet]
public ActionResult ArcGISinit()
{
    YourClass[] yourClassArray = new Yourclass[]{ new Yourclass { number = 555, api = 777, text = "text"} };
    return Json(yourClassArray , JsonRequestBehavior.AllowGet);
}

Would work the same way if you'd use a List<YourClass>

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