简体   繁体   English

Ajax POST 不将 model 发布到 asp.net 核心 6 中的 controller

[英]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.我正在尝试从 Kendo 对话框引发的事件将数据发布到我的 controller。 But, the model is always coming as null. I tried various steps which were mentioned in StackOverflow itself, but none of them works.但是,model 总是以 null 的形式出现。我尝试了 StackOverflow 本身提到的各种步骤,但没有一个有效。

My Ajax call我的Ajax电话

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我的 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.现在捕获的数据被传递给controller。 在此处输入图像描述

You can see the value is getting passed to the controller.您可以看到该值正在传递给 controller。

My Controller我的 Controller

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

My Program.cs file我的Program.cs文件

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我使用[FromBody],[FromForm] - 两者都不起作用
  • Changed datatype in ajax to be text and passed to a method with string as parameter - Did not work将 ajax 中的datatype更改为text并传递给以字符串作为参数的方法 - 无效
  • Tried various ways passing the JSON .尝试了各种方式传递JSON Did not work不工作
  • Changed the JSON to NewtonSoft.Json .JSON更改为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.也许你可以尝试使用 model 创建一个新的 object,我试过了,它工作正常。

You can refer to the following code.你可以参考下面的代码。

Delete.cshtml:删除.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.请注意,您需要使用@model来引用您的 model。

Controller: Controller:

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

Test Result:测试结果:

userRoleDTO用户角色DTO

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.这是由于我在 model 中的一个property中的datatype不匹配。IsActive 在IsActive中是Int并且由于我传递了一个空字符串,所以它没有正确反序列化。

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. requests.Result是我在Ajax调用中传递的JSON数据。 But deserializing was throwing error.但是deserializing是抛出错误。

Once the issue was fixed, changed the input parameter to be [FromBody] UserRoleDTO userRoleDTO and now it has the values inside the input parameter问题解决后,将输入参数更改为[FromBody] UserRoleDTO userRoleDTO ,现在输入参数中包含值

在此处输入图像描述

I still wonder why the actual method in the controller(delete) works even when it cannot match the model datatypes.我仍然想知道为什么 controller(delete) 中的实际方法即使无法匹配 model 数据类型也能正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在asp.net核心中使用ajax将json发布到控制器 - Cannot post json to controller using ajax in asp.net core ASP.Net Core 3 和简单的 POST controller - ASP.Net Core 3 and simple POST the controller ASP.Net Core 3 将 JSON 数组发布到控制器 - ASP.Net Core 3 Posting JSON array to controller AJAX 发布数据到达 ASP.NET Core 2.1.1 控制器时为空 - AJAX post data is null when it reaches the ASP.NET Core 2.1.1 controller 将复杂的 model 传递给 controller 使用 Z9E0DA8438E1E38A1C30F4B76CE3 Core M34A6659BCEAE779F28185E757ABFCA5Z - Passing a complex model to controller using AJAX in ASP.NET Core MVC 在 Asp.net Core MVC 中序列化表单并将其转换为复杂类以使用 Ajax 发布整个模型的问题 - Problems Serializing a Form and Converting It to a Complex Class in Asp.net Core MVC to Post a Whole Model Using Ajax ASP.NET:开机自检列表 <Object> /使用Ajax(JSON)从视图到控制器进行建模 - ASP.NET: POST List<Object> / Model with Ajax (JSON) from view to controller 将AngularJS模型发布到ASP.NET MVC控制器中的复杂模型 - Post AngularJS model to complex model in ASP.NET MVC controller ASP Net Core3.1 AJAX 后发送 NULL 到 Controller - ASP Net Core3.1 AJAX Post Sending NULL to Controller ASP.NET Core - 在没有Ajax的情况下调用javascript中的控制器方法 - ASP.NET Core - Call controller method in javascript without Ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM