OnceJune OnceJune - 7 months ago 15
Javascript Question

MVC: Get JSON data from a controller using AJAX failed

I'm trying to query data using AJAX from a controller, my controller is:

[HttpGet]
public ActionResult GetTestStatus(string userName)
{
var db = new SREvalEntities();
var allTests = db.Tests
.Where(x => string.Equals(x.Owner, userName))
.Select(x => new { CreateDate = x.CreateDate, EndDate = x.EndDate, Status = x.Status })
.OrderByDescending(x => x.CreateDate)
.ToList();

return Json(allTests, JsonRequestBehavior.AllowGet);
}


And my javascript code in an extern file is:

function Filter() {
var userAlias = document.getElementById("UserAliasInput");
var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
$.ajax({
url: '/TestStatus/GetTestStatus',
type: "GET",
dataType: "JSON",
data: { userName: userAlias },
success: function (results) {
$.each(results, function (i, result) {
txt += "<tr><td>" + result.CreateDate + "</td>";
txt += "<td>" + result.EndDate + "</td>";
txt += "<td>" + result.Status + "</td>";
txt += "<td><a href=\"\">Goto</a></td></tr>";
});
}
});
$("#ShowDetail").html(txt);
}


When I tried to debug this function, the code will never excute to

$("#ShowDetail").html(txt);


And my page will never be changed. How can I get it work? Thanks.

Answer

As you are using $.ajax(), which is asynchronous. Thus the $("#ShowDetail").html(txt) is called before the value is returned from API.

You should set the html() after the each block

function Filter() {
    var userAlias = document.getElementById("UserAliasInput");
    var txt = "<tr><th>StartDate</th><th>EndDate</th><th>Status</th><th>Detail</th></tr>";
    $.ajax({
        url: '/TestStatus/GetTestStatus',
        type: "GET",
        dataType: "JSON",
        data: { userName: userAlias.value }, //Use the value property here
        success: function (results) {
            $.each(results, function (i, result) {
                txt += "<tr><td>" + result.CreateDate + "</td>";
                txt += "<td>" + result.EndDate + "</td>";
                txt += "<td>" + result.Status + "</td>";
                txt += "<td><a href=\"\">Goto</a></td></tr>";
            });

            $("#ShowDetail").html(txt); //Move code to set text here
        }
    });    
}