skip to Main Content

I am trying to post data from the front end HTML page to the backend code C# in a MVVM, I will either get a 404 or 400 error while making a lot of testing scenarios (usually the path).

Here is the JavaScript code:

$.ajax({
    type: 'POST',
    url: 'ReportModel/DepAct',
    data: JSON.stringify({ prop1: 'value1', prop2: 'value2' }),
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert('Data sent to backend!');
    },
    error: function (xhr, status, error) {
        alert('Data was not sent to backend!');
    }
});

And this is the backend:

public ActionResult DepAct(List<DepTB> selectedDep)
{
    // Process data as needed
    return new JsonResult(new { success = true });
}

I tried changing the path, data type, give different kinds of data in the front end and in the backend I tried to add different methods with different parameters like just a string, list based on a class etc.

Update 1:

Modified the code to return the same data type and tested one of the answers but no luck

Javascript

var selectedDep = [{ prop1: "value1", prop2: "value2" }];
            $.ajax({
                type: 'POST',
                url: '/Report/DepAct',
                data: JSON.stringify(selectedDep),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert('Data sent to backend!');
                },
                error: function (xhr, status, error) {
                    alert('Data was not sent to backend!');
                }
            });

Someone requested for the class as well

public class DepTB1
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
    }

Method

public ActionResult DepAct([FromBody] List<DepTB1> selectedDep)
        {
            // Process data as needed
            return new JsonResult(new { success = true });
        }

2

Answers


  1. Chosen as BEST ANSWER

    The code is working after adding OnPost in front of the method's name in the class

    [ValidateAntiForgeryToken]
            public IActionResult OnPostDepAct([FromBody] List<DepTB1> selectedDep)
            {
                // Process data as needed
                return new JsonResult(new { success = true });
            }
    

    And using the following kind or URL in the Javascript

    var selectedDep = [{ prop1: "value1", prop2: "value2" }];
                $.ajax({
                    type: 'POST',
                    url: '/Reports/Report?handler=DepAct',
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    data: selectedDep,
                    success: function (data) {
                        alert('Data sent to backend!');
                    },
                    error: function (xhr, status, error) {
                        alert('Data was not sent to backend!');
                    }
                });
    

    Thanks all for trying!


  2. I tried changing the path, data type, give different kinds of data in
    the front end and in the backend I tried to add different methods with
    different parameters like just a string, list based on a class etc.

    Your controller action parameter expecting list but you are sending single object which mismatched with method signature. Another important issue is you are missing [FromBody] because by default ajax request type is application/x-www-form-urlencoded but you are sending json data.

    Assuming you have following class:

    Model:

    public class DepTB
        {
            public string prop1 { get; set; }
            public string prop2 { get; set; }
        }
    

    Modify Ajax code:

    var selectedDep = [{ prop1: "value1", prop2: "value2" }];
    
    
                $.ajax({
                    type: 'POST',
                    url: '/ReportModel',
                    data: JSON.stringify(selectedDep),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert('Data sent to backend!');
                    },
                    error: function (xhr, status, error) {
                        alert('Data was not sent to backend!');
                    }
                });
    

    Note: This would also be correct JSON.stringify([{ prop1: "value1", prop2: "value2" }])

    Add [FromBody] In Controller:

    public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
            {
                // Process data as needed
                return new JsonResult(new { success = true });
            }
    

    Output:

    enter image description here

    Note: You can get more details here in Jquery Official Document

    Update:

    Based on your shared link and description, it appeared that, you are using razor page. While sending ajax request within razor page it requires addition XSRF-TOKEN in header, you could add following code snippet within your ajax request:

    Include XSRF-TOKEN in header:

    headers: {
              RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
             }
    

    You can ignore antiforgery token:

    You even can ignore forgery token by using [IgnoreAntiforgeryToken] before your razor page as following:

    Page Model:

    [IgnoreAntiforgeryToken]
    public class ReportModel : PageModel
    {
        public ActionResult OnPost([FromBody] List<DepTB> selectedDep)
            {
                // Process data as needed
                return new JsonResult(new { success = true });
            }
    }
    

    Ajax:

            $.ajax({
                    type: 'POST',
                    url: '/ReportModel',
                    data: JSON.stringify([{ prop1: "value1", prop2: "value2" }]),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    headers: {
                        RequestVerificationToken:
                            $('input:hidden[name="__RequestVerificationToken"]').val()
                    },
                    success: function (data) {
                        alert('Data sent to backend!');
                    },
                    error: function (xhr, status, error) {
                        alert('Data was not sent to backend!');
                    }
                });
    

    Ouput:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search