0

I have a simple jQuery function that calls a controller action which should return a JSON string. However, I am unable to get the value of the string.

The popup box just says 'undefined'.

I have checked the formatting and also I can see in the console that the JSON gets passed correctly. I am sure that I am missing something completely obvious but cannot find it!

My jQuery function follows

setInterval(function () {
    $.ajax({
        url: "/ImportFile/ImportStatus",
        type: "POST",
        //data: "ID=" + teamID,
        dataType: "json", // type of data you're expecting from response
        success: function (json) {
           alert(json.percentcomplete);    
        },
        error: function (error) {}
    });
}, 10000);

and my controller action

[HttpPost]
public ActionResult ImportStatus()
{
    string json = "{\"percentcomplete\": 10}";
    return Json(new { json = json }); 
}

enter image description here

enter image description here

1 Answer 1

2

You should deserialize the JSON string and return it as an object.

using System.Text.Json;
using System.Text.Json.Serialization;

[HttpPost]
public ActionResult ImportStatus()
{
    string json = "{\"percentcomplete\": 10}";
    return Json(JsonSerializer.Deserialize<ImportStatusResult>(json)); 
}

public class ImportStatusResult
{
    [JsonPropertyName("percentcomplete")]
    public int PercentComplete { get; set; }
}
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.