error 404() when try to make ajax request with type post to function OnPostshiftDataUp

Ahmed Abd El Aziz 315 Reputation points
2023-06-22T11:08:37.1966667+00:00

0

I work on asp.net razor , i get error when try make ajax request to access OnPostshiftDataUp

ERROR : Failed to load resource: the server responded with a status of 400 ()

console.log(formdata) // serialize data

serverip=172.16.224.999&printername=Zebra2&Location=SupervisorOffice&__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTImPtgQsnvTBz4ot8mbln2lEaqGcaT_gzZ-KNNfuEBoqHYSBIdcahXL3LLuum4nfTi2oZDQj-PfodyDAVpa45rYEIb7EcRvHrMn71AyB8PMC6DrqvT8q3cCEcSlt1sYQJ-M

but break point not catch this function meaning not detect there are breakpoint must catch it

the main purpose from ajax request is save data after update data on bootstrap model

what I try for my code

1- function with type post on page model

public ActionResult OnPostshiftDataUp()
        {

            
            return Content("msg");
           
        }

2- ajax request to access function or action OnPostshiftDataUp ajax request i do it

$('#save-btn').click(function () {
                var formData = $('#edit-form').serialize();
                console.log(formData);
            
                $.ajax({
                    url: '?handler=shiftDataUp',
                    
         
                    type: "POST",
                  
                    data: JSON.stringify(formData),
            
                   
                    success: function (result) {
                     
                        $('#edit-modal').modal('hide');
       
                        location.reload();
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                });
            });

bootstrap model then send ajax request when click button save to access function OnPostshiftDataUp

<div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <h5 class="modal-title" style="text-align:center;">
                @*<img src="@Url.Content("~/Img/UserProfile1.png")" alt="ImageProfile" style="width:22%;height:10%" />*@

            </h5>
            <div class="modal-header">
                <h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                  <form id="edit-form" method="post">
                  @*  <input type="hidden" id="edit-id" name="ShiftId">*@
                    <div class="form-group">
                        <label for="edit-server">Server IP</label>
                        <input type="text" class="form-control" id="edit-ip" name="serverip">
                    </div>
                    <div class="form-group">
                        <label for="edit-printer">Printer Name</label>
                        <input type="text" class="form-control" id="edit-printername" name="printername">
                    </div>
                    <div class="form-group">
                        <label for="edit-locationsdata">Location Name</label>
                        <input type="text" class="form-control" id="edit-Location" value="save" name="Location">
                    </div>
                </form>
                @*<div class="form-group row">
                    <label for="serverIp" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">Server IP</label>
                    <div class="col-sm-3">
                        <input id="serverIp" asp-for="User.UserName" readonly type="text" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;" maxlength="30" />
                    </div>
                </div>
            

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary" id="save-btn">Save changes</button>
            </div>
        </div>
    </div>
</div>
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,735 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,566 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,841 Reputation points Microsoft Vendor
    2023-06-23T07:04:46.1266667+00:00

    Hi @Ahmed Abd El Aziz

    ERROR : Failed to load resource: the server responded with a status of 400 ()

    For the 400 error, it might relate the Antiforgery. The Razor Pages is automatically protected from XSRF/CSRF. You should set the XSRF-TOKEN when you want to use the ajax to send request in razor page.

    Check the Program.cs file (asp.net 6+ application), use the following code to register the Antiforgery and set the XSRF-TOKEN header.

    builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    

    Then, in the razor page, before send the request, add the XSRF-TOKEN header. Check the following code:

    Note: I changed the handler's name to "ShiftDataUp", and when send the data, without using the JSON.stringify method to convert to data to json.

                $('#save-btn').click(function () {
                    var formData = $('#edit-form').serialize();
                    console.log(formData); 
                    $.ajax({
                        url: '?handler=ShiftDataUp',
                        type: "POST",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        data: formData,
                        success: function (result) { 
                             alert(result);
                        },
                        error: function (xhr, status, error) {
                            console.log(error);
                        }
                    });
                });
    

    You can check the test page source as below:

    @page "/index1"
    @model RazorWebApp.Pages.Index1Model
    <form id="edit-form" method="post" >
        <div class="modal-body">
    
            @*  <input type="hidden" id="edit-id" name="ShiftId">*@
            <div class="form-group">
                <label for="edit-server">Server IP</label>
                <input type="text" class="form-control" id="edit-ip" name="serverip" value="123.456.789.123">
            </div>
            <div class="form-group">
                <label for="edit-printer">Printer Name</label>
                <input type="text" class="form-control" id="edit-printername" name="printername" value="Hello">
            </div>
            <div class="form-group">
                <label for="edit-locationsdata">Location Name</label>
                <input type="text" class="form-control" id="edit-Location" value="save" name="Location">
            </div>
    
    
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="save-btn">Save changes</button>
        </div>
    </form>
    
    @section Scripts{
        <script>
            $(function(){
                $('#save-btn').click(function () {
                    var formData = $('#edit-form').serialize();
                    console.log(formData); 
                    $.ajax({
                        url: '?handler=ShiftDataUp',
                        type: "POST",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        data: formData,
                        success: function (result) { 
                             alert(result);
                        },
                        error: function (xhr, status, error) {
                            console.log(error);
                        }
                    });
                });
            });
        </script>
    }
    

    Index1.cshtml.cs file:

        public class Index1Model : PageModel
        {
       
            public void OnGet()
            {
            }
    
            [BindProperty]
            public string serverip { get; set; }
            [BindProperty]
            public string printername { get; set; }
            [BindProperty]
            public string Location { get; set; }
            public IActionResult OnPostShiftDataUp(string serverip, string printername, string location)
            {
                return new JsonResult("Success");
    
            }
        }
    

    The result as below:

    image2 If you are meeting the 404 error, the error relates the request url, check it and share with us.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Ahmed Abd El Aziz 315 Reputation points
    2023-06-23T15:10:14.77+00:00

    Thanks for effort but Issue still not solved

    and this is what i do full code sample

    I put break point on public IActionResult OnPostshiftDataUp

    but breakpoint not catched or hit so what I do to solve issue

    program.cs

    builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");   
    
     public class ShelfLabelPrinterSetUpModel : PageModel
        {
     [BindProperty]
            public string serverip { get; set; }
            [BindProperty]
            public string printername { get; set; }
            [BindProperty]
            public string Location { get; set; }
    public IActionResult OnPostshiftDataUp(string serverip, string printername, string location)
            {
                return new JsonResult("Success");
    
            }
    }
    <div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <h5 class="modal-title" style="text-align:center;">
                   
    
                </h5>
                <div class="modal-header">
                    <h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="edit-form" method="post">
                        <div class="form-group">
                            <label for="edit-server">Server IP</label>
                            <input type="text" class="form-control" id="edit-ip" name="serverip">
                        </div>
                        <div class="form-group">
                            <label for="edit-printer">Printer Name</label>
                            <input type="text" class="form-control" id="edit-printername" name="printername">
                        </div>
                        <div class="form-group">
                            <label for="edit-locationsdata">Location Name</label>
                            <input type="text" class="form-control" id="edit-Location"  name="Location">
                        </div>
                        <button type="button" class="btn btn-primary" id="save-btn">Save changes</button>
                    </form>
                  
                    <a href="/"><i class="fas fa-sign-out-alt"></i> Sign Out</a>
    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                  
                </div>
            </div>
        </div>
    </div>
    <table id="editbootstarp">
        <thead>
            <tr>
                <th style="display:none;">ID</th>
                <th>BranchType</th>
                <th>UserPC</th>
                <th>PrinterName</th>
                <th>ArabicConfig</th>
                <th>Status</th>
                <th>Location Name</th>
                <th>>Action</th>
            </tr>
        </thead>
        <tbody>
            
            @foreach (DataRow row in table.Rows)
            {
                <tr>
                    <td style="display:none;">@row["AutoID"]</td>
                    <td>@row["BranchType"]</td>
                    <td>@row["UserPC"]</td>
    
                     <td>@row["PrinterName"]</td>
                    <td>@row["ArabicConfig"]</td>
                    <td>@row["Status"]</td>
                    <td>@row["DisplayName"]</td>
                    <td>
                   <button class="editbt"   data.Location="@row["DisplayName"]" data.printername="@row["PrinterName"]" data.serverip="@row["UserPC"]">Edit</button>
                 </td>  
                </tr>
            }
        </tbody>
    </table>
    @section scripts {
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
        <script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
    
    $(document).ready(function(){
      $('#editbootstarp tbody').on('click', 'tr', function () {
                    // Get the data from the clicked row
                    var rowData = $(this).children('td').map(function () {
                        return $(this).text();
                    }).get();
                    $('#editshelflabelModal #edit-ip').val(rowData[2]);
                    $('#editshelflabelModal #edit-printername').val(rowData[3]);
                    $('#editshelflabelModal #edit-Location').val(rowData[6]);
                    $('#editshelflabelModal').modal('show');
                });
      $('#save-btn').click(function () {
                    var formData = $('#edit-form').serialize();
                    console.log(formData);
                    $.ajax({
                        url: '/?handler=shiftDataUp',
                        type: "POST",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
                        data:formData,
                        success: function (result) {
                            alert(result);
                        },
                        error: function (xhr, status, error) {
                            console.log(error);
                        }
                    });
                });
                
        });
     });
    

    Result of apply all above

    breakpoint not hit or catch function on page model public IActionResult OnPostshiftDataUp and this is main issue

    console.log(formdata)

    serverip=172.16.224.998&printername=Zebra322&Location=DataEntry&__RequestVerificationToken=CfDJ8DvYZnvxyLVKi-zvp3jzTIkAYo94jN3ZNgSd1WmQBm2pv4zlgwNBawaJhzG4sROj2NQ7mDgAU4i-p_1BHUntZg9wNzm8povXvcBehss3xnOJ_yMmRMDuSweMRPCVVXS3L3Q8owl8ZURB3T_R2Zs0aTo

    also success request Done alert

    but not catch post method shiftDataUp

    image for what i try

    Issue function post shiftDataUp not catched

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 69,276 Reputation points
    2023-06-22T17:37:05.4833333+00:00

    razor handler support form posts, so you should use the default. your save button should be type="button", as it is not in a form, nor used to do a form submit

    $('#save-btn ').click(function () {
      var formData = $('#edit-form').serialize();
      $.ajax({
          url: '?handler=shiftDataUp',
          type: "POST",
          data: formData,
          success: function (result) {
             $('#edit-modal').modal('hide');
             location.reload();
          },
          error: function (xhr, status, error) {
              console.log(error);
          }
      });
    )};
    

  3. AgaveJoe 29,281 Reputation points
    2023-06-22T18:38:10.3+00:00

    Replacing the JavaScript/AJAX with a regular browser form post will produce the same results as the JavaScript/AJAX logic.

    @page
    @model RazorPagesDemo.Pages.Bootstrap.IndexModel
    
    
    <div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editshelflabelModal">
            Launch demo modal
        </button>
        <div>
            <div>@Model.serverip</div>
            <div>@Model.printername</div>
            <div>@Model.Location</div>
        </div>
    </div>
    
    
    
    <div class="modal fade" id="editshelflabelModal" tabindex="-1" role="dialog" aria-labelledby="userDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <h5 class="modal-title" style="text-align:center;">
                    @*<img src="@Url.Content("~/Img/UserProfile1.png")" alt="ImageProfile" style="width:22%;height:10%" />*@
                </h5>
                <div class="modal-header">
                    <h5 class="modal-title" id="editshelflabelModaldata" style="margin-left:200px;">Hi,@TempData["UserID"]</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="edit-form" method="post" asp-page-handler="shiftDataUp">
                    <div class="modal-body">
    
                        @*  <input type="hidden" id="edit-id" name="ShiftId">*@
                        <div class="form-group">
                            <label for="edit-server">Server IP</label>
                            <input type="text" class="form-control" id="edit-ip" name="serverip" value="123.456.789.123">
                        </div>
                        <div class="form-group">
                            <label for="edit-printer">Printer Name</label>
                            <input type="text" class="form-control" id="edit-printername" name="printername" value="Hello">
                        </div>
                        <div class="form-group">
                            <label for="edit-locationsdata">Location Name</label>
                            <input type="text" class="form-control" id="edit-Location" value="save" name="Location">
                        </div>
    
    
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" id="save-btn">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    
    
    
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorPagesDemo.Pages.Bootstrap
    {
        public class IndexModel : PageModel
        {
            public void OnGet()
            {
            }
    
            [BindProperty]
            public string serverip { get; set; }
            [BindProperty]
            public string printername { get; set; }
            [BindProperty]
            public string Location { get; set; }
            public ActionResult OnPostshiftDataUp()
            {
                return Page();
    
            }
        }
    }
    
    0 comments No comments

  4. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

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.