Troubleshooting the issue of Ajax POST not properly sending the model data to the controller in ASP.NET Core

I've been attempting to send POST data to my controller from a Kendo dialog event, but I keep encountering the issue of the model being null. Despite trying multiple solutions mentioned on StackOverflow, none have proven effective.

Here is my Ajax call:

function onSubmit(e) {
          
           var myModel={
                  Id:0,
                  RoleNameEn:$('#UserRolePopup').find('#RoleNameEn')[0].value,
                  RoleNameAr:$('#UserRolePopup').find('#RoleNameAr')[0].value,
                  IsActive:$('#UserRolePopup').find('#IsActive')[0].value,
                  CreatedBy:0,
                  CreatedDate:"",
                  ModifiedBy:0,
                  ModifiedDate:""
           };

           $.ajax({
              type: "POST",
              url: "@Url.Action("Delete", "UserRole")", 
              contentType: 'application/json; charset=utf-8',
              data: JSON.stringify(myModel),
              success: function (result) {
                console.log(result);
              },
              error: function (result, status) {
                console.log(result);
              }
            });

        }

Below is my HTML markup:

<div id="example">  
    @(Html.Kendo().Dialog()
    .Name("dialog")
    .Title("Add/Edit User Role")
    .Content("<div id='UserRolePopup'>  <div class='form-group; k-content'> <label for='RoleNameEn'>User role English</label>    <input type='text' class='form-control' id='RoleNameEn' placeholder='Role name in english'/>      </div> <div class='form-group'>    <label for='RoleNameAr'>User role Arabic</label>    <input type='text' class='form-control' id='RoleNameAr' placeholder='Role name in Arabic'>      </div>  <div class='form-check'>        <input class='form-check-input' type='checkbox' value='' id='IsActive'>    <label class='form-check-label' for='IsActive'>Is Active</label>  </div> </div>")
    .Width(400)
    .Modal(true)
    .Actions(actions =>
    {
    actions.Add().Text("Cancel");
    actions.Add().Text("Submit").Primary(true).Action("onSubmit");
    })
    .Events(ev => ev.Close("onClose").Open("onOpen"))
    )
</div>

The captured data is now sent to the controller. https://i.sstatic.net/DnDLr.png

An inspection reveals that the value has been successfully transferred to the controller.

My Controller method:

[HttpPost]
        public JsonResult Delete([FromBody] UserRoleDTO userRoleDTO)
        {
            return new JsonResult(userRoleDTO);
        }

Snippet from my Program.cs file:

builder.Services.AddMvc()
           .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new DefaultContractResolver());

builder.Services.AddControllers().AddNewtonsoftJson();

Attempts made so far:

  • Usage of [FromBody],[FromForm] - Unsuccessful
  • Changing datatype in ajax to text and passing as a string parameter - No luck
  • Trying various techniques of passing the JSON - Ineffective
  • Switching to NewtonSoft.Json - Also did not work

If anyone can pinpoint what configuration might be missing or why this setup is failing, please advise.

Answer №1

Perhaps experimenting with the model to generate a new object could be worth a shot. I tested it out and it seems to work smoothly.

For reference, here is the code snippet:

Delete.cshtml:

@model AjaxTest1.Models.UserRoleDTO
<div id="example">
        <div id='UserRolePopup'>  
            <div class='form-group; k-content'> 
                <label for='RoleNameEn'>User role English</label>    
                <input type='text' class='form-control' id='RoleNameEn' placeholder='Role name in english'/>
            </div> 
            <div class='form-group'>    
                <label for='RoleNameAr'>User role Arabic</label>    
                <input type='text' class='form-control' id='RoleNameAr' placeholder='Role name in Arabic'/>      
            </div>  
            <div class='form-check'>        
                <input class='form-check-input' type='checkbox' value='' id='IsActive'/>    
                <label class='form-check-label' for='IsActive'>Is Active</label>  
            </div> 
        </div>
        <div class="form-group">
                <button type="submit" onclick="onSubmit()">Submit</button>
        </div>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script>
    function onSubmit() {
            @Model mydata=new Object();
            mydata.Id = 0;
            mydata.RoleNameEn = $('#UserRolePopup').find('#RoleNameEn')[0].value;
            mydata.RoleNameAr = $('#UserRolePopup').find('#RoleNameAr')[0].value;
            mydata.IsActive = $('#UserRolePopup').find('#IsActive')[0].value;
            mydata.CreatedBy = "0";
            mydata.CreatedDate = "";
            mydata.ModifiedBy = "0";
            mydata.ModifiedDate = "";
            
            $.ajax({
              type: "POST",
              url: "/Home/Delete",
              contentType: 'application/json',
              data: JSON.stringify(mydata) ,
              success: function (result) {
                alert("success");
                console.log(result);
              },
              error: function (result, status) {
                alert("123");
                console.log(result);
              }
            });
    }
    
</script>

Remember to utilize @model to access your model information.

Controller:

[HttpPost]
public JsonResult Delete([FromBody]UserRoleDTO userRoleDTO)
{
     return Json(userRoleDTO);
}

Test Result:

userRoleDTO

developer tools

Apologies for not being able to directly upload screenshots due to insufficient points.

Answer №2

There was a situation where a datatype mismatch occurred in a specific property within the model. In this case, the IsActive property was defined as an Int in the model, but an empty string was being passed which led to unsuccessful deserialization.

To investigate further, I utilized the following code snippet:

   [HttpPost]
    public JsonResult Delete(UserRoleDTO userRoleDTO)
    {
        using (var bodyReader = new StreamReader(HttpContext.Request.Body))
        {
            Task<string> requests = bodyReader.ReadToEndAsync();

            UserRoleDTO? userRole = JsonSerializer.Deserialize<UserRoleDTO>(requests.Result);
        }

        return new JsonResult(userRoleDTO);
    }

The variable requests.Result contained the JSON data from the Ajax call, but faced issues with the deserialization process.

After resolving the issue, I modified the input parameter to be

[FromBody] UserRoleDTO userRoleDTO
, resulting in successfully receiving values within the input parameter.

https://i.sstatic.net/N2SR7.png

It remains surprising how the delete method in the controller was functioning despite encountering challenges with matching the model datatypes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item. const array = [ {India: { Score: '12', PlayedMatched: '21' } }, { China: { Score: '52', PlayedMatched: '51 ...

Why does Angular not reset form after ng-click event?

Something seems off with my form reset after a ng-click event, am I missing something? I can successfully submit the form, but it doesn't automatically reset. Here is the error message I receive: angular.js:12701 POST 500 (Internal Server Error ...

Is it possible to create a dedicated page in Next.js using static site generation (SSG)?

The static-site generation (SSG) feature of Nextjs allows for fetching data at build time, resulting in pre-rendered pages using getStaticProps and getStaticPaths. Imagine having a blog with numerous articles that remain static, while some may be updated ...

Getting Started with Parsing JSON Objects in ReactJS

In my ReactJS project, I am trying to parse through a JSON list using the following model: public class ModelEmployee { public List<Employeelist> Employees { get; set; } public int count { get; set; } public int Pagenumber { get; set; } ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...

JavaScript is not designed to run a second time

Currently, I have a script set up using $(document).ready(). It works perfectly upon initial loading. However, I also need this script to execute whenever the user changes an HTML select control. Ideally, upon page load, I want the filter and sort functio ...

Tips for integrating Facebook Javascript SDK response into an Ajax request

If I have the following code that retrieves a Javascript object to be viewed in Firebug's console: FB.api('/me',function(apiresponse){ console.log(apiresponse); }); How can I utilize the data from apiresponse in an Ajax request on the ...

Guide on redirecting a URL with AJAX in just 5 seconds!

How can I achieve a redirect to a specific URL after a successful sign-up using AJAX without losing the response from the AJAX call? Below is the code snippet I am currently working with: sign-up.php if ( $stmt->execute() ) { $response['status&ap ...

What is the reason for AngularJS's inclusion of a colon at the end of a data object in an $http post

While attempting to utilize angular js $http for sending a post request to elasticSearch, I encounter an "Unexpected token : " Error. Here is a snippet of my code: var request= $http({ method: "post", url: path, accept:"*/*", headers:{"Co ...

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

Table cell featuring a status menu created with Material UI DataGrid

I'm looking to include a column called "Filled Status." Although I've checked the documentation, I can't quite figure out how to do it. It seems like I may need to use renderCell when setting up the column, but I'm not sure how to make ...

Using the power of AJAX, retrieve data from a PHP script and showcase the response within

Within my HTML file, I have implemented a feature that allows users to input a value. To validate this input, I created a PHP script that checks if the entered value exists in the database. The script returns the following JSON response: {"active":true} ...

Even though I am attempting to submit a form without refreshing the page using Ajax, it is still causing

I've searched high and low, read through numerous examples on various forums, and attempted to find the solution to my query but unfortunately, it still eludes me. Here's the particular scenario I'm facing: Main.php The main.php page featu ...

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Interactive Canvas Feature: Drag and Drop Across Various Objects in HTML 5

I have developed a custom code that enables the creation and rendering of objects on an HTML5 canvas. class Rectangle extends Shape { constructor(options, canvas, type = 'rectangle') { super(...); // inherited from the super class thi ...

Issue with passing props from parent component to child component in Vue.js not functioning

As a newcomer, I have been assigned a project that involves using Vuejs. In this project, there is a page that utilizes a component called DashboardCard. Each DashboardCard receives 2 props - val and icon from the parent component. https://i.stack.imgur. ...

When parsing a DateTimeOffset object, it is necessary to include timezone data

My current challenge involves validating data obtained from an API endpoint where users must input a DateTimeOffset. To address this issue, I have developed my own JsonConverter implementation to ensure the DateTimeOffset is in the correct format. Despite ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. https://i.sstatic.net/MtO8l.png In contrast, highlighted near the red arrows i ...

Accessing data points in jQuery

Here is a sample code I'm working with : <script type="text/javascript"> var currentPicture;//default picture var picEL;//the image viewer element jQuery("#backImageShower").hover( function(i) { picEL = j ...

Acquiring row data upon checkbox selection: A step-by-step guide

I'm struggling to separate and assign the values returned by a function to different parameters. function saveTaxes() { $('input[type=checkbox]').each(function() { if ($(this).is(':checked')) { //test console.log ...