Pedro Mendes
Pedro Mendes

Reputation: 99

ASP.NET MVC get object Id with json

I'm using a jsonResult to receive some object Id, then I try to print in console.log by using $Ajax in view, but the console log is printing undefined instead of some integer value.

Controller action method is returning the id value correctly:

public JsonResult GetLastProcessVersion(int workflowId)
{
    var Workflow = db.Workflows.Find(workflowId);

    // getting the max process id from selected workflow:
    var lastProcessVersion = db.Processes.Where(x => x.WorkflowId == Workflow.Id).Max(y => y.Id);
    return base.Json(lastProcessVersion, JsonRequestBehavior.AllowGet);
}

Then I try to call in Ajax function:

$("#btnVisualize").click(function () {
   $.ajax({
        type: 'POST',
        url: '@Url.Action("GetLastProcessVersion")',
         dataType: 'json',
         data: { workflowId: $("#WorkflowId").val()},
       success: function (res) {
           console.log(res.val);
        },
        error: function (ex) {
            alert('Failed to retrieve info.' + ex);
        }
    });
});

In console log the value is returning "undefined"

Upvotes: 0

Views: 771

Answers (1)

David Liang
David Liang

Reputation: 21476

In your server, the method GetLastProcessVersion is defined as "GET", and your AJAX is trying to "POST" back to the same method. I am surprised you didn't get a 404 or 500 server error because the method the AJAX tries to post back simply is not defined.

Your AJAX function should look like:

$("#btnVisualize").click(function () {
   $.ajax({
       type: 'GET',
       url: '@Url.Action("GetLastProcessVersion", "YOUR CONTROLLER NAME")',
       dataType: 'json',
       data: { workflowId: $("#WorkflowId").val()},
       success: function (res) {
            console.log(res);

            let redirectUrl = '@Url.Action("RedirectMethod", "RedirectController)?v=' + res;

            // similar behavior as an HTTP redirect
            // window.location.replace(redirectUrl);

            // OR similar behavior as clicking on a link
            // window.location.href = redirectUrl;
       },
       error: function (ex) {
           alert('Failed to retrieve info.' + ex);
       }
    });
});

Upvotes: 1

Related Questions