AJAX call to get action result of a Razor model

Neo 421 Reputation points
2023-11-20T04:42:21.9333333+00:00

I just started learning ASP.NET Razor pages. Now I have a need to use AJAX/jQuery to get some data back from a model. I have the following code:

<script type="text/javascript">
function test() {
     $.get('?handler=Echo&msg=hello',
         function (data, status, xhr) {
             $('#result').text(status + ':\n' + data)
         }).fail(function (xhr, status, error) {
             $('#result').text(status + ': ' + error + '\ntext:\n' + xhr.responseText)
         }) }
</script>
public ActionResult<string> OnEcho(string msg) {
     return Content(msg);
}

But it seems ActionResult does not work quite right; insead of getting the echoed back string, I get whole HTML source code instead. What should I do?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,662 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 1,505 Reputation points
    2023-11-20T13:34:34.1633333+00:00

    Working example

        public class TestModel : PageModel
        {
            public void OnGet()
            {
            }
    
            public JsonResult OnGetEcho(string msg)
            {
                return  new JsonResult(msg);
            }
        }
    
    
    
    @page
    @model RazorPagesDemo.Pages.TestModel
    
    <div>
        <button type="button" id="echo">Echo</button>
    </div>
    <div>
        <textarea id="result" name="result" rows="5" cols="50"></textarea>
    </div>
    
    
    @section scripts {
        <script>
            $('#echo').click(function () {
                $.get('?handler=Echo&msg=hello',
                    function (data, status, xhr) {
                        $('#result').text(status + ':\n' + data)
                    }).fail(function (xhr, status, error) {
                        $('#result').text(status + ': ' + error + '\ntext:\n' + xhr.responseText)
                    })
            });
        </script>
    }
    

    https://www.mikesdotnetting.com/article/318/working-with-json-in-razor-pages

    https://www.learnrazorpages.com/razor-pages/handler-methods

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.