0
votes

I am new to AJAX and cant even get the basics to function correctly.

I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.

The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.

Razor Page:

 $.ajax({
        type: "GET",
        url: "/Maps?handler=CanvasBackgroundImage",
            contentType: 'application/json',
            success: function (result) {
                alert(result);
            }
    });

Page Model:

 public JsonResult OnGetCanvasBackgroundImage()
    {
        var result = "test message";
        return new JsonResult(result);
    }
1
Antiforgery is only relevant to POST requests. Have you added "{handler?}" to the @page directive?Mike Brind
Actually, your code works fine for me. 2. "simply shows the HTML layout of the razor page as the message": Did you custom the routes ? 3. Is there a way or a demo that reproduces? 4. As a side note, please change contentType: 'application/json' to dataType: 'application/json' as you didn't send a json request but ask for a json.itminus

1 Answers

0
votes

Below is the code that is now working for me. Thanks for everyone's input.

Razor Page (script section):

 function getMapBackgroundImagePath() {
        // Get the image path from AJAX Query to page model server side.
        $.ajax({
            type: "GET",
            url: "/Maps/Create?handler=MapBackgroundImagePath",
            contentType: "application/json",
            data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
            dataType: "json",
            success: function (response) {
                copyText = response;
                // Run the function below with the value returned from the server.
                renderCanvasWithBackgroundImage();
            },
        });
    }

Page model:

 public JsonResult OnGetMapBackgroundImagePath(string imageId)
    {
        // Get the image full path where the id  = imageId string
        int id = Convert.ToInt32(imageId);
        var imagePath = _context.Image.Where(a => a.ID == id)
            .Select(i => i.ImageSchedule);
        // return the full image path back to js query in razor page script.
        return new JsonResult(imagePath);
    }