Home > Software engineering >  Ajax POST not posting model to the controller in asp.net core 6
Ajax POST not posting model to the controller in asp.net core 6

Time:05-10

I am trying to POST data to my controller from an event raised from Kendo dialog. But, the model is always coming as null. I tried various steps which were mentioned in StackOverflow itself, but none of them works.

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")", //'/UserRole/Create'
              contentType: 'application/json; charset=utf-8',
              data: JSON.stringify(myModel) ,
              success: function (result) {
                console.log(result);
              },
              error: function (result, status) {
                console.log(result);
              }
            });

        }

My HTML

<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>

Now the data captured is passed to the controller. enter image description here

You can see the value is getting passed to the controller.

My Controller

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

My Program.cs file

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

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

Things I tried

  • I used [FromBody],[FromForm] - Both didn't work
  • Changed datatype in ajax to be text and passed to a method with string as parameter - Did not work
  • Tried various ways passing the JSON. Did not work
  • Changed the JSON to NewtonSoft.Json. That also did not work

Can someone tell me if there is any configuration which is missing or why this is not working

CodePudding user response:

Maybe you can try to use the model to create a new object, I tried it, it works fine.

You can refer to the following code.

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 >
                <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>

Please note that you need to use @model to refer to your model.

Controller:

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

Test Result:

enter image description here

I still wonder why the actual method in the controller(delete) works even when it cannot match the model datatypes.

  • Related