[英]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我试过的东西
[FromBody],[FromForm]
- Both didn't work[FromBody],[FromForm]
- 两者都不起作用datatype
in ajax to be text
and passed to a method with string as parameter - Did not workdatatype
更改为text
并传递给以字符串作为参数的方法 - 无效JSON
.JSON
。 Did not workJSON
to NewtonSoft.Json
.JSON
更改为NewtonSoft.Json
。 That also did not workCan 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:测试结果:
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.