skip to Main Content

I have this method in Razor Page code behind which I would like to call using JQuery Ajax

[HttpPost]
    public IActionResult OnPostPopulateMovieDate(int selectedMovieId)
    {
        return new JsonResult("json result");
    }

This is my JQuery code to call the method

 $.ajax({
            contentType: "application/json",
            dataType: 'json',
            type: "POST",
            data: {selectedMovieId:this.selectedIndex},
            url: "/MovieDateHall/Create?handler=PopulateMovieDate",
            success: function () {
                console.log('ok')
            }
        });

I changed my url to url: "/MovieDateHall/OnPostPopulateMovieDate", but still no success.

I put a breakpoint in PopulateMovieDate method and debug it. But it doesn’t reach the breakpoint.

MovieDateHall is the sub-folder name under Pages.

2

Answers


  1. What error are you getting? Did you check the browser console for any javascript error? Please also check the following line exists in your RegisterRoutes method:

    routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

    Login or Signup to reply.
  2. In razor page to call ajax method, you should to ensure the following two points :

    (you can also refer to this link )

    1. Register the Antiforgery-Service
    2. Add the token to your request
    3. Add the antiforgery token to your page either by adding a or by directly using
      the @Html.AntiForgeryToken HtmlHelper

    According to these, you can change your code as follow:

    @page
    @model WebApplication1_rzaor_page.CreateModel
    @{
        ViewData["Title"] = "Create";
        Layout = "~/Pages/Shared/_Layout.cshtml";
    }
    @section Scripts{
        <script>
            $(function () {
                $("#Submit1").click(function () {
                    $.ajax({
                        //contentType: "application/json", // remember to remove this line to ensure pass the correct selectedMovieId 
                        dataType: 'json',
                        type: "POST",
                        data: { selectedMovieId: 1 },
                        url: "/MovieDateHall/Create?handler=PopulateMovieDate",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        success: function () {
                            console.log('ok')
                        }
                    });
                })
    
            })
        </script>
    } 
    
    
    @Html.AntiForgeryToken()
    <input id="Submit1" type="submit" value="submit" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search