I'm trying to send a list of products for my web api in C# via JavaScript but my API doesn't accepts the products. How do I should pass it?
This is my model
public class ProductModels
{
public int productId { get; set; }
public string description { get; set; }
public int quantity { get; set; }
public decimal amount { get; set; }
}
and my API endpoint
[Route("api/pag_seguro/transactions/credit_card")]
public IHttpActionResult DoTransactionWithCreditCard(ProductModels[] products, string senderHash, string cardHash)
in Javascript I'm trying to send it like this
data.products = [{ "productId": 1, "description": "tupperware", "quantity": 1, "amount": 29.80 }];
$.ajax({
type: 'POST',
url: url + '/api/pag_seguro/transactions/credit_card?cardHash=' + cardHash + '&senderHash=' + senderHash,
data: data,
success: function (response) {
console.log(response);
},
dataType: 'json',
async: false
});
and still about this endpoint... how do I send the senderHash and cardHash as POST parameters so that than doesn't appears in web url?
Thank you all
You need to set the content type in the request as
contentType:"application/json"
Also, use JSON.stringify to convert the data to JSON format when you send.
Try this code:
$.ajax({
type: 'POST',
url: url + '/api/pag_seguro/transactions/credit_card?cardHash=' + cardHash + '&senderHash=' + senderHash,
data: JSON.stringify(data),
contentType: "application/json",
success: function (response) {
console.log(response);
},
dataType: 'json',
async: false
});
try this
public IHttpActionResult DoTransactionWithCreditCard([FromUri] SiteInfo, siteInfoProductModels[] products)
and your siteinfo model is
public class SiteInfo
{
public string senderHash { get; set; }
public string cardHash { get; set; }
}
finally remove your route from action header and add new route in webapiconfig.cs like this (and change js file set params liek this /param1/param1 )
config.Routes.MapHttpRoute(
name: "HashRoute",
routeTemplate: "api/{controller}/{action}/{senderHash}/{cardHash}"
);
Related
I have some troubles with transfer json data.
I have some dynamic page. I collect data to json object "Filters".
var Filters = { daterange: $('#daterange').val(), shop: val_shop, pr: val_pr, plan: val_plan, TabsList: TabsList }
$.ajax({
url: "/Reports/Report_2",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(
Filters
)
});
I try get it with JObject.
public IActionResult Report_2() //main Action
{
return View();
}
[HttpPost]
public async Task<IActionResult> Report_2([FromBody]JObject jsonResult)//catch json object
{
//do something
return View(_context.MyDatabase.Result);//return data from database for table(Razor Page)
}
I get Error 415. =(
If I try don't overload Report_2 Action().
$.ajax({
url: "/Reports/Report_2_Filter",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(
Filters
)
});
[HttpPost]
public async Task<JObject> Report_2_Filter([FromBody]JObject jsonResult)
{
return jsonResult;
}
I don't know how return result on Report_2 page. I need result on Report_2 Action becouse I must fill table on Report_2 page. I'm newbee in web, so I will be greateful for any help.
May be you need write ("");
var Filters = { "daterange": $('#daterange').val(), "shop": val_shop, "pr": val_pr, "plan": val_plan, "TabsList": TabsList }
You can add a function to be executed on success. Try to add the following to your ajax request:
success: function(data){
// Do something here
}
Have a look here to see the ajax events.
My solution:
I create class which stores variables:
public class FilterModel
{
public string var1{ get; set; }
public string var2{ get; set; }
public string var3{ get; set; }
public string var4{ get; set; }
public List<string> var5{ get; set; }
}
[HttpPost]
public IActionResult Report_2(FilterModel filter)
{
FilterLogic filterLogic = new FilterLogic(_context);
var result = filterLogic.GetResult(filter);
return View();
}
In JS I use jQuery function $.post
$.post("/Reports/Report_2", { var1: $('#var1').val(), var2: var2, var3: var3, var4: var4, var5: var5});
I'm using dapper to map my database with my mvc project, i have debugged my code to know what's going on and my ReceiveData method isn't receiving the data for some reason when it sends it to my GeoCreate it shows nothing, also i might me wrong because i placed my cursor on my Geo.RouteID, Geo.Latitude,etc and the data was there then it goes to my geography class and after that it's supposed to go to the if statement but it stops there, i'm sending json data with postman.
Here's my ReceiveData method
public bool ReceiveData(Geography Geo)
{
int GeoCreate = this.conn.Execute(#"INSERT GEOGRAPHY([ID_ROUTE],[LAT],[LONG],[BATTERY],[DateCreated],[DEVICE_ID]) values (#Lat,#Long,#Battery,#DateCreated,#Device_ID)",
new { RouteID = Geo.RouteID, Lat = Geo.Latitude, Long = Geo.Longitude, Battery = Geo.Battery, DateCreated = Geo.ObtainedDate, DeviceID = Geo.Device_ID });
if(GeoCreate > 0)
{
return true;
}
return false;
}
Here's the action for calling the ReceiveData method:
[Route("GeoCreate")]
[HttpPost]
public bool StoreLocation(Geography Geo)
{
return GD.ReceiveData(Geo);
}
Here's the javascript code that works for sending my data:
<script>
$(document).ready(function () {
var Geograph = {
Latitude: $("#Latitude").val(),
Longitude: $("#Longitude").val(),
Country: $("#Country").val(),
ObtainedDate: $("#ObtainedDate").val()
};
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.parse( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});
});
</script>
And my Geography class:
public class Geography
{
[Key]
public int RouteID { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Battery { get; set; }
public DateTime ObtainedDate { get; set; }
public int Device_ID { get; set; }
}
Here's the JSON data i'm sending:
{
"Latitude": 19.435547,
"Longitude": -81.77856,
"Battery": 100,
"ObtainedDate":"\/Date(1522600449000)\/",
"Device_ID": 1
}
I'm not setting the RouteID because it fills automatically in the database.
In your ajax call you should use JSON.stringify rather than parse method
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.stringify( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});
I have written a POST request that accepts my Model but once I get into the request the List is returning null.
I have read multiple solutions online from adding [FormBody] to checking my naming conventions but nothing seems to work correctly.
In my Script I create an Array var UserPermissions = new Array();
I then push to the array multiple objects:
var permission = {
UserId: #Model.UserId,
AppId: #Model.AppId,
PermissionId: this.value
}
UserPermissions.push(permission);
Then I perform my Ajax request:
$.ajax({
url: '#Url.Action("UpdateUserPermissions")',
data: JSON.stringify(UserPermissions),
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (status) {
swal("User Permissions have been updated.", { icon: "success" });
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating permissions, please contact support.");
}
});
My Controller POST Request Looks like this:
public IActionResult UpdateUserPermissions([FromBody]PermissionPartialModel model)
{
return View();
}
In every case [FromBody]PermissionPartialModel model is returning null when it should be returning a list.
Here is my Model:
public class PermissionPartialModel
{
public int AppId { get; set; }
public int UserId { get; set; }
public List<UserPermissionsModel> UserPermissions { get; set; }
}
What could be causing this and what is a solution to fix this?
var UserPermissions= {
UserId: #Model.UserId,
AppId: #Model.AppId,
PermissionId: this.value
}
//UserPermissions.push(permission);
$.ajax({
url: '#Url.Action("UpdateUserPermissions")',
data: UserPermissions,
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (status) {
swal("User Permissions have been updated.", { icon: "success" });
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating permissions, please contact support.");
}
});
You are sending an array from view but receive object in controller. You need to change your parameter type from object to list
public IActionResult UpdateUserPermissions([FromBody]List<PermissionPartialModel> model)
{
return View();
}
This will map but you will get UserPermissions null. To solve this you need to make changes in PermissionPartialModel and permission object in view.
permission
var permission = {
UserId: 2,
AppId: 2,
UserPermissions: { PermissionId: 2 }
}
UserPermissions.push(permission);
PermissionPartialModel
public class PermissionPartialModel
{
public int AppId { get; set; }
public int UserId { get; set; }
public UserPermissionsModel UserPermissions { get; set; }
}
Whenever I send 'GET' with JSON.stringify() using AJAX, model value is always accept null;
Why it can only bind 'POST'?
If it is possible, can I use 'GET' and still bind data to model?
Edit: adding Code Example
JS:
$.ajax({
var modelsend = {
itemname: 'shoe',
itemcolor: 'red',
itemsize: '31',
itemvariety: 'SR-31',
}
type: "POST",
url: "#Url.Action("ShowData", "Controller")",
data: JSON.stringify(modelsend),
dataType: "json",
contentType: "application/json",
success: function (data) {
//do something with data
},
error: function (jqXHR, textStatus, errorThrown) {
//show error
}
});
Model:
public class shoemodel
{
public string itemname { get; set; }
public string itemcolor { get; set; }
public string itemsize { get; set; }
public string itemvariety { get; set; }
}
Controller:
public ActionResult ShowData(shoemodel get)
{
List<DataGrid> fetch = func.getdata(get);
return Json(fetch);
}
Perhaps you are forgetting that GET is used for viewing something, without changing it, while POST is used for changing something. And Get can be used to change something only when you use Querystring. Post on the other hand sends form data directly.
HTTP 'GET' method doesn't support a body in the request. The way to send parameters via 'GET' is using the application/x-www-form-urlencoded format appending them in the URL like this.
http://example.com/?key1=value1&key2=value2
I have modeled (no pun intended) my AJAX call on the answer here from logan filley, which seems sensible and likely to work. This is the jquery I have in the View:
$("#btnSaveConfig").click(function () {
var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').checked,
scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').checked,
scheduleFillRate: $('#ckbx_fillratebycustomer_location').checked,
schedulePriceCompliance: $('#ckbx_pricecompliance').checked,
// TODO: Finish this by storing add'l emails in an array along with the three on the page;
recipients: $('#email1').val(),
generationDayOfMonth: $('#dayofmonthselect').val(),
generationOrdinal: $('#ordinalselect').val(),
generationDayOfWeek: $('#dayofweekselect').val(),
generationWeekOrMonth: $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: $('#delperffrom').val(),
daterangeToDeliveryPerformance: $('#delperfto').val(),
daterangeFromFillRate: $('#fillratefrom').val(),
daterangeToFillRate: $('#fillrateto').val(),
daterangeFromPriceCompliance: $('#pricecompliancefrom').val(),
daterangeToPriceCompliance: $('#pricecomplianceto').val()
}
$.ajax({
type:"POST",
url:'#Url.Action("PostUnitConfig", "SaveConfig")',
async:true,
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(saveConfigModel)
});
}); // $("#btnSaveConfig").click()
...and this is my Model:
public class SaveConfigModel
{
public UnitConfigVals unitConfigVals { get; set; }
public class UnitConfigVals
{
public string unit { get; set; }
public bool scheduleProduceUsage { get; set; }
public bool scheduleDeliveryPerformance { get; set; }
public bool scheduleFillRate { get; set; }
public bool schedulePriceCompliance { get; set; }
public List<string> recipients { get; set; }
public int generationDayOfMonth { get; set; }
public string generationOrdinal { get; set; }
public string generationDayOfWeek { get; set; }
public string generationWeekOrMonth { get; set; }
public int daterangeFromProduceUsage { get; set; }
public int daterangeToProduceUsage { get; set; }
public int daterangeFromDeliveryPerformance { get; set; }
public int daterangeToDeliveryPerformance { get; set; }
public int daterangeFromFillRate { get; set; }
public int daterangeToFillRate { get; set; }
public int daterangeFromPriceCompliance { get; set; }
public int daterangeToPriceCompliance { get; set; }
}
}
...and Controller (obviously ultra-spartan at the moment):
public class SaveConfigController : Controller
{
public ActionResult PostUnitConfig(SaveConfigModel model)
{
try
{
string s = model.unitConfigVals.unit;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(new { success = true });
}
}
I am reaching the breakpoint in my Controller (on the "string s = model.unitConfigVals.unit;" line), but it throws an exception because the value of "model" is null. Why? Have I got something in my AJAX call wrong, or...?!?
UPDATE
I changed my jquery to this (changed boolean assignments and appended a semicolon):
$("#btnSaveConfig").click(function() {
var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').attr('checked'),
scheduleDeliveryPerformance:
. . .
};
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
//contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ data: saveConfigModel })
});
});
...but the Controller is still passed a null model.
UPDATE 2
Now I changed "attr('checked')" to "is('checked')" but no difference...
UPDATE 3
"model" is null here in the Controller:
public class SaveConfigController : Controller
{
public ActionResult PostUnitConfig(SaveConfigModel model)
...when the AJAX call is like this:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
dataType: "json",
data: saveConfigModel
});
...and also when the AJAX call is like this:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
data: saveConfigModel
});
...and this:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});
Do I need the "async: true"? I don't use that in my (working) GET AJAX calls. Similarly, do I need "cache: false"? I do use that in those working GET AJAX calls...
UPDATE 4
Even when I provide just some bogus vals:
var saveConfigModel = {
unit: 'Buford', //$('#unitsselect').val(),
scheduleProduceUsage: true, //$('#ckbx_produceusage').is(':checked'),
scheduleDeliveryPerformance: false, // $('#ckbx_deliveryperformance').is(':checked'),
scheduleFillRate: false, //$('#ckbx_fillratebycustomer_location').is('checked'),
schedulePriceCompliance: false, //$('#ckbx_pricecompliance').is('checked'),
// TODO: Finish this by storing add'l emails in an array along with the three on the page; might be as easy as declaring an array like this one, and adding to it as necessary
recipients: 'platypus#whatever.com', // $('#email1').val(),
generationDayOfMonth: '2nd', //$('#dayofmonthselect').val(),
generationOrdinal: 'First', //$('#ordinalselect').val(),
generationDayOfWeek: 'Thursday', // $('#dayofweekselect').val(),
generationWeekOrMonth: 'month', // $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: '1', // $('#delperffrom').val(),
daterangeToDeliveryPerformance: '1', //$('#delperfto').val(),
daterangeFromFillRate: '1', //$('#fillratefrom').val(),
daterangeToFillRate: '1', //$('#fillrateto').val(),
daterangeFromPriceCompliance: '1', //$('#pricecompliancefrom').val(),
daterangeToPriceCompliance: '1' //$('#pricecomplianceto').val()
};
...it still winds up at the Controller null like forevermore before.
And then, grasping at straws, I even encased the boolean values in single quotes ('true' and 'false'), but that also (probably predictably) made no difference either.
UPDATE 5
For future generations, this is the AJAX that works:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});
Since the values you posting back are for your nested UnitConfigVals class (not SaveConfigModel, then you controller method should be
public ActionResult PostUnitConfig(SaveConfigModel.UnitConfigVals model)
and the ajax data option needs to be
data: JSON.stringify({ model: saveConfigModel })
Alternatively you could keep the current controller method and use
data: JSON.stringify({ model: { unitConfigVals: saveConfigModel }})
although it seems a little odd that you using a nested class here.
A few other issues with your initial code
$('#ckbx_produceusage').checked will return undefined, and it
needs to be $('#ckbx_produceusage').is(':checked') which will
return true or false
Since recipients is List<string>, it will need to be
recipients: [ 'someValue', 'anotherValue', etc ]
However all this code to build you json data not really necessary, and if your view is generated correctly using the strongly typed HtmlHelper methods, then your ajax call can be as simple as
$.ajax({
type:"POST",
url:'#Url.Action("PostUnitConfig", "SaveConfig")',
dataType: "json",
data: $('form').serialize(),
success: function(data) {
// do something
}
});