C# JSON Post From JavaScript - c#

I have the following 2 classes which hold the data:
public class ItemList{
public IList<Item> Items{get;set;}
}
public class Item{
public int id {get;set}
public string name {get;set}
}
My controller looks like:
public virtual JsonResult SaveItems(ItemList items)
{}
I try to post a JS object like this:
var toPost = { "items" : [ {"id" : 1, "name":"test}, {"id" : 1, "name":"test"}] }
$.ajax({
type: "POST",
url: "URL TO POST TO",
dataType: "json",
data: toPost,
traditional: true,
success: function (data, status, request) {
if (data.Error != undefined) {
alert("System Error: " + data.Error);
return;
}
console.log("Success");
},
error: function (request, status, error) {
console.log("ERROR");
}
});
I do a console.log before i post it and the data looks as desribed in the toPost variable but when debugging on C# side the ItemList items is null

Use JSON.stringify in toPost and set the content type
$.ajax({
...
contentType: "application/json; charset=utf-8"
data: JSON.stringify(toPost),
...
});

Your SaveItems method is expecting an ItemsList object and what is being sent in the request is a string. You will need to deserialise the request data into your ItemsList object something like the following:
public virtual JsonResult SaveItems(String jsonRequest)
{
ItemsList items = Util.JsonSerializer.Deserialize<ItemsList>(jsonRequest);
// further processing of items
}

Related

Unable to pass values to MVC Controller via AJAX

I have an MVC controller which takes an int and a complex object
[HttpPost]
public async Task<JsonResult> AddComment(int ticketId, TicketReply ticketReply)
Even if I take out the object, I can't seem to pass a simple value. Here's what the AJAX call looks like
var dataObject = {
ticketId: ticketId //, ticketReply: { Attachements: attachements }
};
$.ajax({
url: $('#updateTicketURL').val(),
data: dataObject, //, //JSON.stringify(dataObject), //JSON.stringify(dataObject),
type: 'POST',
//dataType: 'JSON',
contentType: 'application/json',
success: function (data) {
console.log(data);
}
})
I have tried every combination of JSON.stringyfy etc. but I never seem to get the value. Even if I replace with static values it never seems to work.
You need an object model that matches the data being sent
public class DataObject {
public int ticketId { get; set; }
public TicketReply ticketReply { get; set; }
}
next you update the controller action to expect the data using the [FromBody] attribute so that the model binder can create and populate the sent data
[HttpPost]
public async Task<JsonResult> AddComment([FromBody]DataObject dataObject) {
int ticketId = dataObject.ticketId;
TicketReply ticketReply = dataObject.ticketReply;
//...
}
Finally you need to send the data correctly from the client.
var dataObject = {
ticketId: ticketId ,
ticketReply: { Attachements: attachements }
};
$.ajax({
url: $('#updateTicketURL').val(),
data: JSON.stringify(dataObject),
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});

Receive json object through ajax post request

UNABLE TO DETECT PROBLEM
I am trying to get data from server using ajax post request but when ajax request hits back end c# method its data part gets null
here is my js code
let da = '{"sidx":'+sid+',"idx":'+cur+'}';
da = JSON.parse(da);
$.ajax({
type: "POST",
url: "../RegSaleman/next",
data: {x:da},
datatype: "Json",
complete: function (dataret) {
}
});
and c# code is
[HttpPost]
public JsonResult next(JsonResult x)
{
}
You're trying to read JsonResult, which is wrong. This class used for response from server.
You can create some data model (simple class) that will be mapped automatically by MVC framework.
Let's assume that you have JSON object:
{
"id": "someValue",
"foo" : 3,
"bar" : "bar string"
}
and you can create a class
public class MyClass
{
public string Id {get;set;}
public int Foo {get;set;}
public string Bar {get;set;}
}
As you can see, it even can map variables in different case (like Foo and "foo"), but this behavior could be altered in case of need.
And your method will be:
[HttpPost]
public JsonResult next(MyClass x)
{
}
var obj = new Object();
$.ajax({
type: "POST",
url: "/RegSaleman/next",
data: JSON.stringify(o),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
},
error: function (response) {
}
});

What is wrong with my Ajax code in my case using ASP.net?

I have data like this
[{"billno":"111","amount":"2233.00"},{"billno":"222","amount":"2500.00"},{"billno":"333","amount":"3000.00"}]
I want to store this record in my database, So before that I am trying to send this records to server
Here is my AJAX code:
$('#btnAddVendor').click(function () {
var values = [];
$('table#ContentPlaceHolder1_GridView1 input.checkBoxClass:checked').each(function () {
var $row = $(this).closest('tr').children('td');
values.push({ 'billno': $row.eq(1).text(), 'amount': $row.eq(5).text() });
});
//html_data = JSON.stringify(values);
alert(JSON.stringify(values)); // this alert will display above values
$.ajax({
type: 'POST',
url: 'GPCreateCheque.aspx/setCheqVendorSearchEntry',
data: JSON.stringify(values),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result.d);
},
error: function (result) {
alert("Not save");
}
});
})
WebMethod code
public partial class WebForm5 : System.Web.UI.Page
{
[WebMethod]
public static string setCheqVendorSearchEntry(vendorEntry[] values)
{
//here I will write the code to store the records in database
return "Success"; //for testing I return this string
}
}
public class vendorEntry{
public string billno { get; set; }
public string amount { get; set; }
}
I don't know how to receive from ajax. Thanks
Update Error msg
http://localhost:55047/GPCreateCheque.aspx/setCheqVendorSearchEntry 500 (Internal Server Error)
I finally make it run by following:
You need to make it allowed for POST method
[System.Web.Services.WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public static string setCheqVendorSearchEntry(vendorEntry[] values)
{
return "Success"; //for testing I return this string
}
and Default.aspx, your Json Array was not proper. You need to take parameter name (here it is 'values' in setCheqVendorSearchEntry method) in json element and pass it as string or serialize.
var values = '{ "values": [{ "billno": "111", "amount": "2233.00" }, { "billno": "222", "amount": "2500.00" }, { "billno": "333", "amount": "3000.00" }] }';
$.ajax({
type: 'POST',
url: 'Default.aspx/setCheqVendorSearchEntry',
data: values,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result.d);
},
error: function (result) {
console.log(result);
}
});
For your learning purpose:
When you console your error in ajax error section, you can find exact error in browser console like this:
Image : https://prnt.sc/gw06sr

pass value to controller by using ajax

I want to pass value from view to controller by using ajax.
<button onclick="addCommentByAjax()" >Save</button>
My script:
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
data: {
choiceId: "1"
}
});
}
Controller:
[HttpPost]
public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
{
//
}
but choiceId always null
Change couple of things.
First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post.
$('#btnComment').click(function () {
var choiceId = $('#YourChoiceId').val();
$.ajax({
url: '/Survey/DoDetailSurvey',
data: { 'choiceId' : choiceId},
type: "post",
cache: false,
success: function (response) {
//do something with response
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error occured');
}
});
});
Then your controller should look like this
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example.
In case you want to pass viewmodel you should construct your data object like this:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
Sample structure of SurveyViewModel I assume:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}
Since there are two parameter in your controller, you need to identify them both form the client side. Further, you should specify the contentType.
You spread the payload like so:
function addCommentByAjax() {
var payload = {
model: {
// whatever properties you might have
},
choiceId: 1
};
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
contentType: 'application/json',
data: JSON.stringify(payLoad)
});
}
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
You can also pass like this
or for more parameters
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}

JS Array is not received by c# webapi

I have a test js function that should post data to webapi by Post method
function test() {
var puffs = [];
var puffObject = {
id: "2735943",
priority: "1"
};
puffs.push(puffObject);
puffs.push(puffObject);
var dto =
{
po: puffs
};
$.ajax({
type: "POST",
url: "../api/PuffPriority/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dto),
dataType: "json",
success: function (data, status) {
if (data) {
console.log("Welcome");
} else {
console.log("No data");
}
},
error: function (error) {
console.log("Error");
}
});
}
In the controller class i have
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
where PuffPriority Model is
public class PuffPriority
{
public string id { get; set; }
public string priority { get; set; }
}
I dont know whats wrong , the values are sent by JS but api Controller don't fetch it :( Please help, i have already wasted a lot of time.
You have a bug in your code.
Simply change
url: "../api/PuffPriority/"
to
url: "../api/Post/"
or change your method name from Post to PuffPriority
Changed
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
To
[FromBody]List<PuffPriority> po{
//Do something here with po, but po is always empty
}

Categories

Resources