locked
Json results return as UNDEFINED ??? RRS feed

  • Question

  • User-973886032 posted

    Hi guys

    I am using Razor action results to post/receive Ajax updates, however its returning UNDEFINED

    Here is my code, does anyone know what is wrong here ?

    it does hit the breakpoint where I have the Json return page on the server, but the client page alert shows UNDEFINED

    <script>
        $(document).ready(function () {
    
    
          var  AddAntiForgeryToken = function (data) {
                data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
                return data;
            };
    
            var T  = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
    
            var tobesent = { Mobile: "mobile", Forgery : T}
            ehioze(tobesent);
    
            return;
    
    
            function ehioze(tobesent) {
    
                $.ajax({
                    type: "post",
                    dataType: "html",
                    url: $(this).attr("rel"),
                    data: AddAntiForgeryToken({ id: parseInt($(this).attr("title")) }),
                    success: function (message) {
    
                     
                     
                        console.log(JSON.stringify(message.t));
                        alert(JSON.stringify(message.t));
                        alert('The Fight goes on');
                    },
                    error: function (message) {
                           alert(message.t);
                   
                    }
                });
    
    
    
    
    
    /// and action results page
    
    
     public IActionResult OnPostAsync()
            {
                var message = new
                {
                    t = "1"
                };
    
                
                return new JsonResult(message);
            }
    
    
    

    Thursday, August 27, 2020 1:38 PM

Answers

  • User475983607 posted

    Here is my code, does anyone know what is wrong here ?

    We're missing code but what I can see shows you are not following the rules.   Define a route handlers which allows you to call the post method using the URL.  Otherwise, you need to use a query string; ?handler=message. 

    Razor pages use a naming convention.  A post method starts with "OnPost" followed by the method name used in the AJAX function.

    The example below injects the antiforgery token.  Using the form tag helper does the same thing.

    @page "{handler?}"
    @model RazorDemo.Pages.ajax.JsonExModel
    @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery antiforgery
    @{
        ViewData["Title"] = "Json Ex";
        var token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
    }
    
    
    <div>
        <input id="Button1" type="button" value="button" />
    </div>
    <div id="result"></div>
    
    @section Scripts
    {
        <script>
            $('#Button1').click(function () {
    
                $.ajax({
                    type: "post",
                    url: "/ajax/JsonEx/Message",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    headers: {
                        RequestVerificationToken: '@token'
                    },
                    success: function (response) {
                        console.log(response);
                        $('#result').text(response.t)
                    },
                    error: function (response) {
                        console.log(response);
                    }
                });
            });
    
        </script>
    }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection.Metadata.Ecma335;
    using System.Security.Policy;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorDemo.Pages.ajax
    {
        public class JsonExModel : PageModel
        {
           
            public void OnGet()
            {
            }
            
    
            public IActionResult OnPostMessage()
            {
                var message = new
                {
                    t = "1"
                };
    
                return new JsonResult(message);
            }
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 27, 2020 3:38 PM

All replies

  • User475983607 posted

    Here is my code, does anyone know what is wrong here ?

    We're missing code but what I can see shows you are not following the rules.   Define a route handlers which allows you to call the post method using the URL.  Otherwise, you need to use a query string; ?handler=message. 

    Razor pages use a naming convention.  A post method starts with "OnPost" followed by the method name used in the AJAX function.

    The example below injects the antiforgery token.  Using the form tag helper does the same thing.

    @page "{handler?}"
    @model RazorDemo.Pages.ajax.JsonExModel
    @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery antiforgery
    @{
        ViewData["Title"] = "Json Ex";
        var token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
    }
    
    
    <div>
        <input id="Button1" type="button" value="button" />
    </div>
    <div id="result"></div>
    
    @section Scripts
    {
        <script>
            $('#Button1').click(function () {
    
                $.ajax({
                    type: "post",
                    url: "/ajax/JsonEx/Message",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    headers: {
                        RequestVerificationToken: '@token'
                    },
                    success: function (response) {
                        console.log(response);
                        $('#result').text(response.t)
                    },
                    error: function (response) {
                        console.log(response);
                    }
                });
            });
    
        </script>
    }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection.Metadata.Ecma335;
    using System.Security.Policy;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorDemo.Pages.ajax
    {
        public class JsonExModel : PageModel
        {
           
            public void OnGet()
            {
            }
            
    
            public IActionResult OnPostMessage()
            {
                var message = new
                {
                    t = "1"
                };
    
                return new JsonResult(message);
            }
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 27, 2020 3:38 PM
  • User-973886032 posted

    thank you

    however its not hitting the break point, here is my code. Its for a shopping cart, built from scratch. Found at Pages >> Cart >> Index.cshtml

    @page "{handler?}"
    @model VirtualMarkets.Web.Pages.Cart.IndexModel
    
    
    @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery antiforgery
    
    @{
        ViewData["Title"] = "Shopping basket";
        var token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
    }
    
    @section scripts
        {
        @try
        {
    
            <script>
        $(document).ready(function () {
    
    
    
            $('#Button1').click(function () {
    
                $.ajax({
                    type: "post",
                    url: "/Cart/Index/Modifications",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    headers: {
                        RequestVerificationToken: '@token'
                    },
                    success: function (response) {
                        console.log(response);
                        $('#result').text(response.t)
                    },
                    error: function (response) {
                        console.log(response);
                    }
                });
            });
    
     });
    

    and here is my handler

      public IActionResult OnPostAsyncModifications() 
            {
     
                var message = new
                {
                    t = "1"
                };
    
                
                return new JsonResult(message); 
            }

    Thursday, August 27, 2020 5:30 PM
  • User475983607 posted

    afrika

    however its not hitting the break point, here is my code. Its for a shopping cart, built from scratch. Found at Pages >> Cart >> Index.cshtml

    Remove the button click handler.   My example code used a button for testing.  Your design does not use a button...  Also change the AJAX URL so it matches your design.

    Thursday, August 27, 2020 5:59 PM
  • User-973886032 posted

    This works, but one more question

    when I try to run it using Async it does not work ? 

    e.g. instead of using  OnPostMessage() I use  OnPostAsyncMessage() the latter does not work

    Thursday, August 27, 2020 9:20 PM
  • User475983607 posted

    e.g. instead of using  OnPostMessage() I use  OnPostAsyncMessage() the latter does not work

    I assume you think adding "Async" to the end of "OnPost" makes the method async.  That's not the case.   The OnPost, OnGet, OnPut, naming convention apply to the Razor Pages framework and HTTP.  Asycn/await is a .NET language level programming pattern used across all platforms.  

    Friday, August 28, 2020 1:28 AM
  • User-973886032 posted

    thanks for the explanation

    Monday, August 31, 2020 9:39 PM