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 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 });
}
CodePudding user response:
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; }
}