I am having issue: I am sending multiple parameters to my Ajax handler method, one is an object (consumer), others are string and int, but in the method, I’m always getting null.
Can anyone help me?
Client-side code:
var PartyUpdate = parseInt($('#hfIsPartyChange').val(), 10);
// debugger;
console.log(consumer);
$.ajax({
type: 'POST',
url: getRootPath() + '/AjaxHandlers/Details?handler=UpdateConsumer',
headers: {
'RequestVerificationToken': token
},
// data: '{Consumer:' + JSON.stringify(consumer) + '}',
data: JSON.stringify({ Consumer: consumer, UpdateConsumer: PartyUpdate, ChannelOfContactibility: "MAIL" }),
// data: JSON.stringify( consumer ),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
Web service method:
public class UpdateConsumerRequest
{
public Consumer Consumer { get; set; }
public Int32 UpdateConsumer { get; set; }
public string ChannelOfContactibility { get; set; }
}
public IActionResult OnPostUpdateConsumer([FromBody] UpdateConsumerRequest request)
{
// Access the Consumer object
Consumer Consumer = request.Consumer;
Int32 UpdateConsumer =1 ; // Set default value of 1 if not provided
// Access the ChannelOfContactibility value
string ChannelOfContactibility = "MAIL";
// ....
}
1
You can refer to the following code to builder the JS Object and send data to Razor page’s handler method.
$(function(){
$("#btnsubmit").click(function(){
var consumer = {};
consumer.Id=1001;
consumer.Name = "John";
var PartyUpdate =1002;
$.ajax({
type: "POST",
url: "Index?handler=UpdateConsumer",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, //add the verification token to the header.
data: JSON.stringify({ Consumer: consumer, UpdateConsumer: PartyUpdate, ChannelOfContactibility: "MAIL" }),
contentType: 'application/json; charset=utf-8',
});
});
});
Handler method:
public IActionResult OnPostUpdateConsumer([FromBody] UpdateConsumerRequest request)
{
// Access the Consumer object
Consumer Consumer = request.Consumer;
Int32 UpdateConsumer = 1; // Set default value of 1 if not provided
// Access the ChannelOfContactibility value
string ChannelOfContactibility = "MAIL";
// ....
return new JsonResult(Request);
}
The output as below: