Alexandre Lima
Alexandre Lima

Reputation: 324

Ajax e Asp.net MVC return "result is undefined"

Javascript:

$(function () {
    $("#btEmail").click(function () {
        var name = $("#username").val();

        $.post("@Url.Action("SearchUserByUsername", "LogonWorkFlow")", { username: name }, function (result) {
            var r = result;

        });
    });
});

Controller MVC:

[HttpPost]
        public ActionResult SearchUserByUsername(string username)
        {
            return Json(GetUserByEmail(username), JsonRequestBehavior.AllowGet);
        }

public async Task<JsonResult> GetUserByEmail(string email)
        {
            var u = await userManager.FindByEmailAsync(email);

            var user = new { mail = u.Email, n = u.FullName };

            return Json(user, JsonRequestBehavior.AllowGet);
        }

The request usually passes by function, but the return is always empty

Upvotes: 0

Views: 338

Answers (1)

David
David

Reputation: 219057

You're not retuning a string, you're returning a task. Which the JSON serializer doesn't know what to do with and which has no meaningful string representation to return to the client. SearchUserByUsername should also be async. Something like:

public async Task<ActionResult> SearchUserByUsername(string username)
{
    return Json(await GetUserByEmail(username), JsonRequestBehavior.AllowGet);
}

That way it can await the call to GetUserByEmail, which is async.


Although since GetUserByEmail already returns a JsonResult you can (and probably should) simplify:

public async Task<ActionResult> SearchUserByUsername(string username)
{
    return await GetUserByEmail(username);
}

Of course, at this point it begs the question of why you really need the SearchUserByUsername operation in the first place, since it's just a pass-through to an existing operation.

Upvotes: 2

Related Questions