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
[FromBody],[FromForm]
- Both didn't workdatatype
in ajax to be text
and passed to a method with string as parameter - Did not workJSON
. Did not workJSON
to 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.
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:
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.