How to send right model - javascript

I send model with ajax on server with post request.
I have next model and a controller that has a method of fasting.
public class TestDto: BaseDto
{
[Required]
public ProductGalleryDto GalleryProduct { get; set; }
public int? RetailPriceEur { get; set; }
[Required]
public int? AmountSpc { get; set; }
public bool? PrizeSent { get; set; }
public string Comment { get; set; }
public DateTime? StartDate { get; set; }
[Required]
public DateTime? ExpirationDate { get; set; }
public bool IsParticipant { get; internal set; }
}
public override IActionResult Post([FromBody] TestDto item)
{
if (!IsAdmin)
return BadRequest(ApiErrorCodes.InsufficientPriveleges);
if (!ModelState.IsValid)
return BadRequest(ApiErrorCodes.RequiredFieldsMissing, ModelState.Keys.FirstOrDefault());
}
JS:
var object = JSON.stringify({
createddate: startdate,
retailpriceeur: price,
amountspc: spobicoinprice,
prizesent: false,
expirationdate: expirationdate,
comment: comment,
productgalleryid: productgalleryDto
});
$.ajax({
headers: { "Authorization": "Bearer " + localStorage.getItem('authToken') },
url: "/api/testapi/",
method: "post",
data: object,
contentType: "application/json; charset=utf-8",
success: function (result) {
}
});
Fields in js are also present in the model
Actual: model is not valid.
How me fix that? Please, help

You Shroud send an object not JSON string in ajax request as this example :
var person = new Object();
person.name = "name";
person.surname = "surname";
$.ajax({
url: 'http://localhost:3413/api/person',
type: 'POST',
data: person,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});

Related

Posting to mvc controller action always return error

I am new to mvc and I am tring to use ajax to get and post data. Get is working fine but when I use post using the same ajax code while change it to post give me always error 400. I tried with many type of data sent and the action in the controller is empty to eleminate that the error occour there although i new 400 error is a bad request but I couldn't figure it out.
The code is as follow
async function SaveTheDay(url, data) {
if (data != null) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: data,
success: function (response) {
if (response) {
console.log("Ok");
} else {
console.log("not valid ");
}
},
error: function (req, status, error) {
console.log("error "+status+" "+error);
}
})//not null
}
}//SaveTheDay
the controller action is :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SaveDay(InfoDay day)
{
return View("DayTrial");
}
and I call the function when the save button cliked as:
//define the object
var infoDay =
{
userId :userId,
date: TheDate.value ,
items :items ,
itemsAmount : itemsAmount,
itemsMealTime :itemsMealTime,
dailyConsumedkCal: dailyConsumedkCal,
dayTotal :"",
bloodData :"",
bloodSugarData :"",
sleepData :"",
indexData :"",
dayCost :0
}
SaveTheDay("/Days/SaveDay", infoDay);
here is the InfoDay class
public class InfoDay
{
public int userId { get;
set; }
public string date { get; set;
}
public string? items { get;
set; }
public string? itemsAmount {
get; set; }
public string? itemsMealTime {
get; set; }
public int? dailyConsumedkCal
{ get; set; }
public string? dayTotal {
get; set; }
public string? bloodData {
get; set; }
public string? bloodSugarData
{ get; set; }
public string? sleepData {
get; set; }
public string? indexData {
get; set; }
public int? dayCost { get;
set; } = 0;
}
The ValidateAntiForgeryToken attribute prevents 'Cross-site request forgery' attacks in your MVC application.
See https://learn.microsoft.com/..../security/anti-request-forgery?view=aspnetcore
Do not remove it.
To avoid the 400 error, you must pass the token with your POST request.
async function SaveTheDay(url, data) {
if (data != null) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('RequestVerificationToken',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
if (response) {
console.log("Ok");
} else {
console.log("not valid ");
}
},
error: function (req, status, error) {
console.log("error "+status+" "+error);
}
})//not null
}
}//SaveTheDay
Of course the hidden field with the token has to be present in the view.
The HTML Helper Html.AntiForgeryToken includes the token.
#Html.AntiForgeryToken()
If you use a form tag helper, the token is also included.
See https://learn.microsoft.com...?view=aspnetcore-6.0#the-form-tag-helper

Http post method seen as http get method

I have this javascript snippet :
$.ajax({
type: "Post",
contentType: 'application/json',
url: "../api/Pointage/GetPointages",
data: JSON.stringify({
laDate: DateConsultation,
lstcols: Collaborators,
lEquipe: equipe,
Type: 3,
}),
success: function (data) {
console.log(data);
call3(data);
}
});
the signature of the service method is the following :
[HttpPost]
public List<ItemStatistiquesPointageMonth> GetPointages(Nullable<System.DateTime> laDate = null, List<Collaborateur> lstcols =null, Nullable<int> lEquipe = null, int Type = -1)
When I make the call, the serive is unreachable !!
So what is the reason of this problem ? How can I fix it?
Create a model class which reflect the object you create in the client
public class dataModel
{
public Nullable<System.DateTime> laDate { get; set; }
public List<Collaborateur> lstcols { get; set; }
public Nullable<int> lEquipe { get; set; }
public int Type { get; set; }
}
And then add it to the method with the FromBody attribute
[HttpPost]
public List<ItemStatistiquesPointageMonth> GetPointages([FromBody] dataModel data){}
Create a Model with your paramaters and pass it to your post method
[HttpPost]
public List<ItemStatistiquesPointageMonth> GetPointages([FromBody] MyModel model)
also use dataType: "json"

How to pass a object with list object from javascript to controller in .Net

I am currently trying to send an object with a list, but I do not understand why sends the object but the list I receive zero.
Structure:
public class Provider
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Articles> Articles { get; set; }
}
public class Articles
{
public int Id { get; set; }
public string Name { get; set; }
}
Javascript
var articles = [];
articles.push({ Id: 1, Name: "Article Name 1" });
articles.push({ Id: 2, Name: "Article Name 2" });
var provider = {
Id: 1,
Name : "Provider Name",
Articles : articles
};
And i used this call ajax
$.ajax({
contentType: 'application/json; charset=utf-8',
url: "/Provider/Save",
type: 'post',
dataType: 'json',
data: JSON.stringify({ provider: provider}),
cache: false,
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
Controller
[HttpPost]
public ActionResult Save(Provider provider)
{
// Code here
return View();
}

Passing JSON to a Controller with Multiple Models and/or Parameters via AJAX POST

I wrote this Controller:
[HttpPost]
public JsonResult CheckOut(List<POS_model> pos, double totalPayment)
{
try
{
var json = JsonConvert.SerializeObject(pos);
DataTable posTable = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
posTable.Columns["discount_percent"].ColumnName = #"Discount %";
POS m_pos = new POS();
m_pos.Data = posTable;
m_pos.totalPayment = totalPayment;
m_pos.CheckOut();
return Json(new
{
Status = "Success"
});
}
catch
{
return Json(new
{
Status = "Fail"
});
}
}
And i attempted wrote this AJAX script to call and submit the parameters to the Controller:(but it didn't work)
var totalPay = 1000;
var GatherPosItems = $('#tblPOS').tableToJSON();
$.ajax({
type: 'POST',
data: JSON.stringify(GatherPosItems)+"&totalPayment="+totalPay,
url: '#Url.Action("CheckOut", "POS")',
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert('Success');
},
error: function (req, status, errorObj) {
alert(errorObj.toString());
}
});
The GatherPosItems is a JSON with multiple "Rows" or Objects, so it's an array.
I added a parameter totalPayment.
How can i pass Both GatherPosItems and totalPayment to the Controller?
my Model:
public class POS_model
{
public string Qty { get; set; }
public string description { get; set; }
public string price { get; set; }
public string discount_percent { get; set; }
public string Discount_amount { get; set; }
public string Discounted_price { get; set; }
public string Line_total { get; set; }
public string is_vat { get; set; }
public string track_type { get; set; }
public string item_line_id { get; set; }
public string id { get; set; }
public string sale_code { get; set; }
public string reference { get; set; }
public string unit_of_measure { get; set; }
public string location { get; set; }
public string item_code { get; set; }
}
My GatherPosItems's RESULT:
You concatenate a non-JSON string (&totalPayment="+totalPay) to the JSON returned from JSON.stringify function, which corrupts the format of data being sent to the server and makes the model binder unable to parse it.
The following should work:
$.ajax({
type: 'POST',
data: JSON.stringify({pos: GatherPosItems, totalPayment: totalPay}),
url: '#Url.Action("CheckOut", "POS")',
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert('Success');
},
error: function(req, status, errorObj) {
alert(errorObj.toString());
}
});

Sending LIst<t> via ajax to complex model

I know I've done this before but I can't seem to get this to work.
I have the following JavaScript;
$("#btnTestVouchers").click(function () {
var postData = {
"workplaceGiverId": $(".wpgDropdownList").val(),
"fromMemberId": $(".wpgFromMemberDropdownList").val(),
"toMemberId": $(".wpgToMemberDropdownList").val(),
"voucherExpiryDate": $("#expiryDatePicker").val(),
"recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]")
};
console.log(postData);
$.ajax({
type: "POST",
url: "/Admin/TestVoucherCreationEmails",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(postData),
success: function (d) {
alert("OK");
},
error: function (xhr, textStatus, errorThrown) {
alert("Error:" + errorThrown);
}
});
});
In my model I have;
public class postDataObject
{
public int workplaceGiverId { get; set; }
public int fromMemberId { get; set; }
public int toMemberId { get; set; }
public string voucherExpiryDate { get; set; }
public IEnumerable<BulkVoucherRecipient> recipients { get; set; }
}
public class BulkVoucherRecipient
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string voucheramount { get; set; }
}
In my controller I have;
[HttpPost]
public void TestVoucherCreationEmails(postDataObject postedData)
{
string g = "";
}
However when I post, the list of recipients is always empty.
If I don't Stringify the list of recipients I get the same result.
Anyone know what I'm doing wrong?
edit
The other values all come through ok, just the List is empty.
You don't need to JSON.stringify the recipients.
"recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]")
Remove JSON.stringify form here and it should work.
var postData = {
"workplaceGiverId": $(".wpgDropdownList").val(),
"fromMemberId": $(".wpgFromMemberDropdownList").val(),
"toMemberId": $(".wpgToMemberDropdownList").val(),
"voucherExpiryDate": $("#expiryDatePicker").val(),
"recipients": [{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]
};
Try this, It should work
[HttpPost]
public void TestVoucherCreationEmails([FromBody]postDataObject postedData)
{
string g = "";
}

Categories

Resources