简体   繁体   中英

Ajax POST not posting model to the controller in asp.net core 6

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. 在此处输入图像描述

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

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

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:

userRoleDTO

developer tools

Sorry I don't have enough points so I can't upload screenshots directly.

It was due to a datatype mismatch in one of my property in the model. IsActive is Int in model and since I was passing an empty string it was not deserializing properly.

I debugged this by using the below code

   [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);
    }

requests.Result was having he JSON data which I pass in the Ajax Call. But deserializing was throwing error.

Once the issue was fixed, changed the input parameter to be [FromBody] UserRoleDTO userRoleDTO and now it has the values inside the input parameter

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM