Asked by:
ASP.NET MVC get object Id with json

Question
-
User1787915951 posted
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 printingundefined
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" since the res is not giving any value at all.
Monday, September 2, 2019 4:25 PM
All replies
-
User1787915951 posted
resolved with removing .val on res paramenter, the res will give the value that i need.
Monday, September 2, 2019 4:51 PM -
User753101303 posted
Hi,
What if using
console.log(res); // you return an integer, not an object with a val property
Monday, September 2, 2019 4:55 PM -
User-1038772411 posted
Hi Pratykus,
You pass Model :
// 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);
=> lastProcessVersion attached Debugger and check the return data after Ajax In check. Like lastProcessVersion model pass {id,name} then Ajax Call Is.
console.log(res.val); //wrong bcz of not pass data or undefined console.log(res.name); //Right
Please Refer This Link May Help You: https://www.c-sharpcorner.com/blogs/get-the-data-from-asp-net-mvc-controller-using-jquery-ajax-and-bind-it-to-the-textbox
Tuesday, September 10, 2019 5:27 AM -
User-1151440187 posted
you have to return res
$("#btnVisualize").click(function () { $.ajax({ type: 'POST', url: '@Url.Action("GetLastProcessVersion")', dataType: 'json', data: { workflowId: $("#WorkflowId").val()}, success: function (res) { console.log(res); }, error: function (ex) { alert('Failed to retrieve info.' + ex); } }); });Wednesday, September 11, 2019 4:26 AM