Why is the model binding not working? ASP.NET Core 5.0 RazorPages - asp.net-core

ASP.NET Core 5.0 Razor Pages.
When posting the array, the model is not binding - value is showing empty array.
This is a JSON array posted using Ajax -
[
{ "Order":1, "FileName":"bbed5ecf-4133-4681-b0f3-c11366ad3186.jpg" },
{ "Order":2, "FileName":"737e60dc-0631-493d-947d-2f5948d7818c.jpg" },
{ "Order":3, "FileName":"6c76f9d1-44bd-4b80-926e-2ce4307eb30b.jpg"}
]
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(newOrderDictionary),
success: function (response) {
}
});
}
RazorPage action Method
public async Task OnPostAsync(ImageOrder[] data)
{
}
public class ImageOrder
{
public int Order { get; set; }
public string FileName { get; set; }
}

The data parameter of the POST should be the object value, not a stringified version of it. Try changing to:
...
data: newOrderDictionary,
...
Assuming newOrderDictionary is an array.

Considering using post to pass data, you need to add contentType:"application/json" in ajax.
$.ajax({
type: "POST",
url: "/?handler",
dataType: "json",
contentType:"application/json",
//...
});
In addition, add [FromBody] in the bakend.
public async Task OnPostAsync([FromBody]ImageOrder[] data)
{
}
Then, it can get the data.

Turns out that this works :
public async Task OnPostAsync(ImageOrder[] order)
{
}
function UpdateImageOrder() {
$.ajax({
type: "POST",
url: "/property/imagesorter",
dataType: "json",
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: {
order: newOrderDictionary
},
success: function (response) {
}
});
}

Related

ASP.NET Core AJAX POST not returning error, however, not saving data

I am using a button OnClick event to try and save a record to a database using AJAX in ASP.NET Core. The function is not returning an error, however, the data is not being saved. I am just trying to test with hard coded data first. A record with AdapollingProjectProcessStatusId = 1 exists in the database.
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
contentType: "application/json",
data: JSON.stringify({ "id": 1, "status": 'test'}),
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
LiveAdapollingProjectProcessStatusController:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
return Json(processstatus);
}
LiveAdapollingProjectProcessStatus.cs:
namespace CPSPMO.Models.PMO
{
public partial class LiveAdapollingProjectProcessStatus
{
public int AdapollingProjectProcessStatusId { get; set; }
public string AdapollingProjectProcessStatus { get; set; }
}
}
Please let me know if you are able to help me with this AJAX Post.
Thanks
Not sure how do you store it to the database, but the way you pass parameter to backend by ajax should be like below:
function SendHtmlEditorValueToController(data) {
$.ajax({
type: 'POST',
url: '#Url.Action("AJAXPost", "LiveAdapollingProjectProcessStatus")',
//contentType: "application/json", //remove this...
data:{ "id": 1, "status": 'test'}, //modify here...
dataType: 'json',
success: () => {
console.log("value is sent");
},
error: (error) => {
console.log(JSON.stringify(error));
}
});
}
After reviewing the comments regarding missing code for saving the data in the database, I modified the controller:
[HttpPost]
public JsonResult AJAXPost(int id, string status)
{
LiveAdapollingProjectProcessStatus processstatus = new LiveAdapollingProjectProcessStatus
{
AdapollingProjectProcessStatusId = id,
AdapollingProjectProcessStatus = status
};
//save it in database
var result = _context.LiveAdapollingProjectProcessStatuses.Update(processstatus);
_context.SaveChanges();
return Json(processstatus);
}
It is saving the data to the database now. Thanks for the help

I cannot find a way to update calendar events on mssql. Posting to my razor page does not work (400 error)

Code to update with a custom button in the calendar:
myCustomButton: {
text: 'Save Events',
click: () => {
var allevents = calendar.getEvents();
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: allevents,
url: '/Wishes/Individual/Update',
headers: {
'RequestVerificationToken': '#antiforgery.GetAndStoreTokens(HttpContext).RequestToken'
},
success: function (response) {
alert: ('success');
},
failure: function (response) {
alert: ('failure');
}
});
}
},
According to your description and code, it seems that you'd like to post all events within FullCalendar to your Razor Page handler by making AJAX Post Request(s), and then save/update events on database.
To achieve the requirement, you can refer to the following example.
On JavaScript Client
customButtons: {
myCustomButton: {
text: 'Save Events',
click: function () {
var allevents = calendar.getEvents();
var events = [];
$.each(allevents, function (index, event) {
//console.log(event);
// include only expected data (such as title, start and end etc) in json object `newevent`
// instead of all information of calendar event
var newevent = { "title": event.title, "start": event.start, "end": event.end };
events.push(newevent);
});
$.ajax({
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(events),
url: '/Wishes/Individual/Update',
headers: {
'RequestVerificationToken': '#antiforgery.GetAndStoreTokens(HttpContext).RequestToken'
},
success: function (response) {
alert: ('success');
},
failure: function (response) {
alert: ('failure');
}
});
alert('clicked the custom button!');
}
}
},
Razor page handler method
public IActionResult OnPostUpdate([FromBody]List<Event> events)
{
//code logic here
return Content("ok");
}
Custom Event class
public class Event
{
public string title { get; set; }
public string start { get; set; }
public string end { get; set; }
// defind other properties
// such as groupId, url etc based on your requirements
}
Test Result

JSON not mapped to Class

I have a asp.net core 3.0 application with WebPages and I try to send a JSON via ajax to my handler. But the parameter is always null or just filled with the default values. I tried to if the JSON string from the post is parseable and it works when I parse manually.
This is my controller:
public void OnPost([FromBody]FilterModel filter)
{
Console.Write(filter);
}
This is the model class:
public class FilterModel
{
public DateTime TimeRangeFrom { get; set; }
public DateTime TimeRangeTo { get; set; }
public int CustomerId { get; set; }
}
The ajax request:
$.ajax({
url: "/CustomerOverview/Test",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
CustomerId: customerId,
TimeRangeFrom: picker.startDate,
TimeRangeTo: picker.endDate
}),
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function(response) {
button.hide();
},
failure: function(response) {
alert(response);
}
});
And the JSON as logged in Chrome Dev Tools:
{CustomerId: "1", TimeRangeFrom: "2019-08-26T22:00:00.000Z", TimeRangeTo: "2019-09-25T21:59:59.999Z"}
Do I have to setup a mapping or something?
FromBody attribute will parse the model the default way which in most cases are sent by the content type application/json from the request body.So if you fill a form and pass the form data to the controller action,you need to convert the JavaScript object into a string with JSON.stringify().
FromForm attribute is for incoming data from a submitted form sent by the content type application/x-www-url-formencoded.
Reference:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.0#sources
Turns out that it can't convert an "1" to an int. I had to convert the value for customerId to a int first so that I have this JSON:
{
"CustomerId": 1,
"TimeRangeFrom": "2019-08-26T22:00:00.000Z",
"TimeRangeTo": "2019-09-25T21:59:59.999Z"
}

How to configure WCF RESTful endpoint for client-side jQuery calls

Can some one show me how to configure the WCF Endpoint for the following RESTful Web Service to be called from a JQuery Ajax call. My example service code:
namespace MyService
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebGet(UriTemplate = "/GetDepartment")]
public Department GetDepartment()
{
... code
};
return data;
}
}
jQuery code:
var jData = {};
$.ajax({
cache: false,
type: "POST",
async: true,
url: "MyService/GetDepartment",
data: JSON.stringify(jData),
contentType: "application/json",
dataType: "json",
success: function (jsondata) {
... code
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Try following-
function SaveBook() {
var bookData = {};
$.ajax({
type: “POST”,
url: “MyService/GetDepartment″,
data: JSON.stringify(bookData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}

How to Send Json String to Controller in mvc4 and Deserialize json

I have the json object like below
Extension = {
"BookMarks":
[{"Name":"User1","Number":"101"},
{"Name":"User2","Number":"102"},
{"Name":"User3","Number":"103"}]}
I want to send this json string to my controller Action method and Deserialize the data
I want to pass the data to the partialview
public ActionResult ExtensionsDialog(var data)
{
return PartialView(data);
}
Any help
Thanks in advance..
In your View:
function SendData(){
var dataToSend = JSON.stringify(data);
$.ajax({
type: "POST",
url: '#Url.Action("YourAction", "YourController")',
dataType: "json",
data: dataToSend,
contentType: "application/json; charset=utf-8",
});
}
$("#Updatebtn").click(function () {
sendData();
});
In you Model:
public class YourModel
{
public String Name { get; set; }
public int Number { get; set; }
}
In your Controller:
[HttpPost]
public ActionResult YourAction()
{
var resolveRequest = HttpContext.Request;
List<YourModel> model = new List<YourModel>();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
model = (List<YourModel>)serializer.Deserialize(jsonString, typeof(List<YourModel>);
}
//Your operations..
}
Hope this helps.
I don't think you have to read the input stream yourself. If you provide a model the binder should do it for you.
In your code behind:
public class StatusInfo
{
public int ItemId { get; set; }
public int StatusId { get; set; }
}
[HttpPost]
public ActionResult EditStatus(StatusInfo info)
{
DoSomethingInteresting(info.ItemId, info.StatusId);
return new EmptyResult();
}
And just use the jQuery ajax function like so:
function changeStatus(itemId, statusId) {
var postData = { "ItemId": itemId, "StatusId": statusId };
$.ajax({
url: "/Item/EditStatus",
type: "POST",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
console.log("success updating status.");
},
error: function () {
console.log("error updating status.");
}
});
}
You can call the action and pass values like this. Just substitute your data with the data I have in the data section.
$.ajax({
url: '/Schedule/Schedule/Create',
type: 'POST',
cache: false,
datatype: JSON,
data: {
scheduleName: ScheduleName,
description: Desc,
Hol_Type: JSON.stringify(holidaytype),
Start_Date: start_date,
End_Date: end_date,
Start_Time: StartTime,
End_Time: EndTime,
days: JSON.stringify(days),
rec_type:1
},
success: function (data, status) {}});
You can pass your data via an ajax call like this :
$.ajax({
url : "#Url.Action("YourMethod", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({Extension: data})
}).done(function (result) {
//Check if it's OK
}).fail(function (result) {
//Check if it is not OK
}).always(function() {
//Some code executed whatever success or fail
})
.done, .fail and .always are not compulsory, it's just better in my opinion.
Then use it in your Controller as you've done.
It should be OK.
Your script should be like:
Extension = {"BookMarks":[{"Name":"User1","Number":"101"},{"Name":"User2","Number":"102"},{"Name":"User3","Number":"103"}]}
$.ajax({
url : "#Url.Action("ExtensionsDialog", "Controller")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : {"data" : Extension }
});
Action method is same.
public ActionResult ExtensionsDialog(var data)
{
return PartialView(data);
}