I am trying to post a list of data and a variable to WebApi using jQuery Ajax.
My clientside code is:
var datatopost = new Object();
for(var i=0;i<results.length;i++)
{
datatopost["[" + i + "].NodeID"] = results[i];
}
var result;
result = grandtotal;
$.ajax({
type: "POST",
url: createurl,
dataType: "json",
traditional: true,
data: "{ 'node': '" + datatopost + "',ttl: '" + result + "'}",
statusCode: {
200: function () {
alert("success");
}
},
error:
function (res) {
alert('Error');
$("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText);
}
});
My server-side code is
public HttpResponseMessage PostBuy([FromBody]List<Node> node, decimal ttl)
{
//Success code here
return new HttpResponseMessage(HttpStatusCode.OK);
}
I am receiving a bad request error in the network tab of the inspect element.
Is there any problem with my code?
I'm not completely sure, but it may be related to the "node" element in your JSON. It looks to be an object and not an array. Verify that the data is being sent properly in its JSON form.
here is my way to post a list with some other values, I post a JSON.stringify string,
var o = {};
o.UserCode = userCode;
o.Role = role;
o.UserId = r.d;
o.Hotels = [];
$('#hotel-list li :checkbox:checked').each(function () {
var ctrl = $(this);
var h = {};
h.ChainId = ctrl.val();
h.ProjectId = ctrl.next().val();
h.CityId = ctrl.next().next().val();
o.Hotels.push(h);
});
$.post("/home/UpdateDataToDb/", { d: JSON.stringify(o) }, function (r) {
alert(r.Msg);
});
and my server side code is this:
[System.Web.Mvc.HttpPost]
public JsonResult UpdateDataToDb(string d)
{
var jsonStr = d;
var json = JsonConvert.DeserializeObject<QueryPostData>(jsonStr);
//json.UserCode
//json.Role
//json.UserId
foreach (var chain in json.Hotels)
{
//My code to handle list `Hotels`
}
}
and the QueryPostData is this
public class QueryPostData
{
public string UserCode { get; set; }
public string Role { get; set; }
public string UserId { set; get; }
public List<BriefChain> Hotels { get; set; }
}
public class BriefChain
{
public string ChainId { get; set; }
public string ProjectId { get; set; }
public string CityId { get; set; }
}
Related
public Class MainModel
{
public IFormFile PDF { get; set; }
public List<TempModel> List1{ get; set; }
public List<TempModel1> List2 { get; set; }
}
public class TempModel
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
}
public class TempModel1
{
public string Prop1{ get; set; }
public string Prop2{ get; set; }
public List<TempModel> list1 { get; set; }
}
function AJAXCall()
{
var list1 = [{Prop1: "abcd",Prop2: "abcd1"},{Prop1: "abcd123",Prop2: "abcd456"}]
var list2 = [{Prop1: "abcd",Prop2: "abcd1",list1:list1 },{Prop1: "abcd123",Prop2: "abcd456",list1:list1}]
formData.append("PDF", files[i]);
formData.append("List1", list1);
formData.append("List2", list2);
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});
}
public IActionResult Save([FromBody] MainModel model, IFormFile PDF)
{
}
I tried almost everything. Can you please help to get these details to be sent to the server-side?
In Controller, I am not getting any values from AJAX Call.
URL is correct, it is hitting the Controller Action Method but values are returning null.
What is the correct way to accomplish this task as I Have tried many things but it did not work out.
Here is a demo:
View:
<input type="file" id="images" multiple />
<button onclick="AJAXCall()">ajax</button>
#section scripts{
<script>
function AJAXCall() {
var formData = new FormData();
var files = $("#images").get(0).files;
formData.append('PDF', files[0]);
var list1 = [{ Prop1: "abcd", Prop2: "abcd1" }, { Prop1: "abcd123", Prop2: "abcd456" }]
var list2 = [{ Prop1: "abcd", Prop2: "abcd1", list1: list1 }, { Prop1: "abcd123", Prop2: "abcd456", list1: list1 }]
for (var i = 0; i < list1.length; i++) {
formData.append("List1[" + i + "].Prop1", list1[i].Prop1);
formData.append("List1[" + i + "].Prop2", list1[i].Prop2);
}
for (var i = 0; i < list2.length; i++) {
formData.append("List2[" + i + "].Prop1", list2[i].Prop1);
formData.append("List2[" + i + "].Prop2", list2[i].Prop2);
for (var j = 0; j < list1.length; j++) {
formData.append("List2[" + i + "].list1[" + j + "].Prop1", list1[j].Prop1);
formData.append("List2[" + i + "].list1[" + j + "].Prop2", list1[j].Prop2);
}
}
$.ajax({
type: "POST",
url: "Save",
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});
}
</script>
}
Controller:
public IActionResult Save(MainModel model)
{
return Ok();
}
result:
I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.
function FileSenderAPI(){
var DictionaryData = new Object;
DictionaryData = document.getElementById("hidFilePath").value;
var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
$.ajax({
url: Url,
method: 'Get',
data Type: "json",
data: {
ModelsPath:JSON.stringify(DictionaryData),
Exchange: exchange,
Exchange_key: key,
},
success: function (data, textStatus, xhr) {
alert(data);
},
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``
Here is a solution. You can try it. Hope to help, my friend :))
1) Create a model
public class DictionaryModel
{
public Dictionary<string, string> dict { get; set; }
public string Exchange { get; set; }
public string Exchange_Key { get; set; }
}
2) Action
[HttpPost]
public JsonResult Example(DictionaryModel model)
{
// Your Logic
return Json("Success");
}
3) In View
$('#btClick').on('click', function () {
var dict = {};
dict["id"] = "200";
dict["Name"] = "Chris";
dict["DynamicItem1"] = "Item 1";
var theObject = {};
theObject.dict = dict;
theObject.Exchange = "Abc";
theObject.Exchange_Key = "123";
let url = '#Url.Action("Example","Home")';
$.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
console.log("success");
}, "json");
});
I have a model. I used it for a while webform. But I am new on asp.net mvc. Little knowledge on this subject. I want you to help me with this. I have to get the data with ajax.Please help me.
public class BasketModel
{
public int id { get; set; }
public int name { get; set; }
public int summary { get; set; }
public int price { get; set; }
public int quantity { get; set; }
public int image { get; set; }
}
I used to my model on controller. And converted to json. and returned.
public JsonResult Test()
{
BasketModel basket = new BasketModel
{
id = 1,
name = 1,
image = 1,
price = 1,
quantity = 1,
summary = 1
};
var jsonSerializer = new JavaScriptSerializer();
var jsonbasket = jsonSerializer.Serialize(basket);
return Json(jsonbasket,JsonRequestBehavior.AllowGet);
}
I want the script object to be as follows on index.cshtml
$('.my-cart-btn').myCart({
showCheckoutModal: true,
cartItems : {
"id":1,
"name":1,
"summary":1,
"price":1,
"quantity":1,
"image":1
}
}),
I want to do this with ajax like below.
cartItems :
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Product/Test',
success: function (data) {
alert(data);
} ,
data: JSON.stringify(data),
error: function(jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
}),
Looks like you are unnecessarily serializing it. The Json method is capable of sending the object as JSON back to the client.
public JsonResult Test()
{
var basket = new BasketModel
{
id = 1,
name = 1,
image = 1,
price = 1,
quantity = 1,
summary = 1
};
return Json(basket,JsonRequestBehavior.AllowGet);
}
The latest versions of MVC uses Newtonsoft Json.NET serializer behind the screen. The msdn documentation of JavaScriptSerializer also recommends to use JSON.NET
Now in your success event, you can use the JSON object as needed.
success: function (data) {
$('.my-cart-btn').myCart({
showCheckoutModal: true,
cartItems : data
});
} ,
Hi below is my question.
How to send Javascript array object to the MVC5 controller method.
The code successfully hit the action method but the list value param value is null. I tried different combination with the JSON.stringify as well.
//object class
public class MassPayoutItem
{
public string ReciverEmailID { get; set; }
public string Amount { get; set; }
public int ProviderID { get; set;}
public string AppintmentsID { get; set; }
public string TransictionID{get;set;}
public string TransictionStatus { get; set; }
public string ProviderName { get; set;}
}
//Action method
public ActionResult GetProviderMassPaymentDetail(List<MassPayoutItem> PayoutItemList){
return Json(new { Result = true, ResultData = ResaultData, Message = "" }, JsonRequestBehavior.AllowGet);
}
//JavaScript Code
function MassPay() {
alert("called MassPay");
var MassPymentList = new Array();
var objs;
$('.Include_Payment:checked').each(function () {
var ReciverEmailId = $(this).parents('tr').attr("emailid");
var appointmentids = $(this).parents('tr').attr("appointmentids");
var ProviderID = $(this).parents('tr').attr("UserId");
var Amount = $(this).parents('tr').find(".Amount").text();
var ProviderName = $(this).parents('tr').find(".OwnerName").text();
MassPymentList.push({ "ReciverEmailID": ReciverEmailId, "Amount": Amount, "ProviderID": ProviderID, "AppintmentsID": appointmentids, "ProviderName": ProviderName, "TransictionID": "abc", "TransictionStatus": "bcd" });
});
objs = JSON.stringify({ "PayoutItemList": MassPymentList });
debugger;
// _PageUrl.PayMassTransiction
// '#Url.Action("GetProviderMassPaymentDetail","Controller")'
//The call hits the method but the value is null
$.ajax({
Type: "POST"
, url: _PageUrl.PayMassTransiction
, contentType: "application/json,charset=utf-8",
traditional: true
, data: objs,
datatype: "json",
success: function (result) {
debugger;
alert("called");
}
, error: function (result) {
}
});
}
Hi Finally I solve the issue.
public class MassPayoutItem
{
public string ReciverEmailID { get; set; }
public string Amount { get; set; }
public int ProviderID { get; set;}
public string AppintmentsID { get; set; }
public string TransictionID{get;set;}
public string TransictionStatus { get; set; }
public string ProviderName { get; set;}
}
//Action method
**//This is first change i have make.**
[HttpPost, ActionName("GetProviderMassPaymentDetail")]
public ActionResult GetProviderMassPaymentDetail(List<MassPayoutItem> PayoutItemList){
return Json(new { Result = true, ResultData = ResaultData, Message = "" }, JsonRequestBehavior.AllowGet);
}
//JavaScript Code
function MassPay() {
alert("called MassPay");
var MassPymentList = new Array();
var objs;
$('.Include_Payment:checked').each(function () {
var ReciverEmailId = $(this).parents('tr').attr("emailid");
var appointmentids = $(this).parents('tr').attr("appointmentids");
var ProviderID = $(this).parents('tr').attr("UserId");
var Amount = $(this).parents('tr').find(".Amount").text();
var ProviderName = $(this).parents('tr').find(".OwnerName").text();
MassPymentList.push({ "ReciverEmailID": ReciverEmailId, "Amount": Amount, "ProviderID": ProviderID, "AppintmentsID": appointmentids, "ProviderName": ProviderName, "TransictionID": "abc", "TransictionStatus": "bcd" });
});
objs = JSON.stringify({PayoutItemList: MassPymentList });
debugger;
// _PageUrl.PayMassTransiction
// '#Url.Action("GetProviderMassPaymentDetail","Controller")'
//The call hits the method but the value is null
// below is the changed ajax calll change Type to type
$.ajax({
type: "POST"
, url: _PageUrl.PayMassTransiction
, contentType: "application/json,charset=utf-8"
,async: false
,traditional: true
, data: objs,
datatype: "json",
success: function (result) {
debugger;
alert("called");
}
, error: function (result) {
}
});
}
I'm trying to post an array of values back to my action method, but with no luck as I'm getting a null for 'ParcelList'. Upload Files argument is being populated, just having a problem with ParcelList.
//ParcelList returning null
public ActionResult Add(AddShipmentVM model, ParcelVM[] ParcelList, HttpPostedFileBase[] UploadFiles )
{
if (ModelState.IsValid)
{
return RedirectToAction("Home", "CustomClearence");
}
return View(model);
}
ParcelVM
public class ParcelVM
{
[Required(ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "RequiredValue")]
public string TrackTrace { get; set; }
[Required(ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "RequiredValue")]
[RegularExpression(#"^\d{0,3}\.?(\d{3,3})*,?\d{1,2}$", ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "InvalidWeight")]
public string GrossWeight { get; set; }
public decimal Parcelno { get; set; }
}
Ajax
When user clicks on finish, submit form
$(".actions a[href=#finish]").click(function () {
var form = jQuery('#addShipmentForm').serializeObject();
var parcelList = $.parseJSON(ko.toJSON(viewModel.parcelList()));
var tariffList = $.parseJSON(ko.toJSON(viewModel.tariffList()));
var dashBoardurl = '#Url.Action("Home","Shipment")'
var tariffObject = JSON.stringify({ TariffList: tariffList });
$('#uploadDocument input[type=file]')[0].files }
var UploadFiles = { UploadFiles: $('#uploadDocument input[type=file]')[0].files }
$.extend(form, { FinancialAndCustomsModel: tariffObject });
$.extend(form, { ParcelList: parcelList });
$.extend(form, UploadFiles);
$.ajax({
type: "POST",
data: form,
contentType: false,
success: function (result) {
if (result.status == "success") {
$(location).attr('href', dashBoardurl);
}
else {
//$(location).attr('href', addRequestUrl);
}
},
cache: false,
processData: false
});
});