I have en array that looks like this:
[Object { OldData="(3) Lindrigt skadad", NewData="(9) Uppgift saknas", AccidentNumber=1173590}]
I make a Jquery-post as below to ASP.NET:
$.ajax({
type: "POST",
url: DataReview.BASE + "/UOS/SaveUOSChangeLog",
data: postData,
success: function (data) {
//alert(data.Result);
},
dataType: "json",
traditional: true
});
Here Is my controller:
public ActionResult SaveUOSChangeLog(List<String> values)
{
try
{
var fish = Json(new { Data = values });
return Json(new { Result = "True", ResultData = values }, JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json(new { Result = "Fail", Message = "Faaaaaail" }, JsonRequestBehavior.AllowGet);
}
}
When I debug this, the value of values is [0] = "[object Object]"
How can I access the actually values from the array?
EDIT:
I have created the following model:
public class UOSChangeLogFrontEnd
{
public int AccidentNumber { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
public int Action { get; set; }
}
An my controller looks like this:
public ActionResult SaveUOSChangeLog(List<UOSChangeLogFrontEnd> values)
{
try
{
var fish = Json(new { Data = values });
return Json(new { Result = "True", ResultData = values }, JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json(new { Result = "Fail", Message = "Faaaaaail" }, JsonRequestBehavior.AllowGet);
}
}
But the value count Is 0 when I debug.
Create a model like this, instead of using String as a model.
public class AccidentModel
{
public int AccidentNumber { get; set; }
public string OldData { get; set; }
public string NewData { get; set; }
}
Then used it in your action like this:
public ActionResult SaveUOSChangeLog(AccidentModel accident)
{
//..use your model
}
Try this:
Model:
public class Object
{
public string OldData { get; set; }
public string NewData { get; set; }
public string AccidentNumber { get; set; }
}
public class RootObject
{
public Object Object { get; set; }
}
Controller:
public ActionResult SaveUOSChangeLog(List<RootObject> values)
JavaScript:
[{
"Object": {
"OldData": "(3) Lindrigt skadad",
"NewData": "(9) Uppgift saknas",
"AccidentNumber": "1173590"
}
}]
Related
I am trying to pass multiple parameters using ajax 'data:'. In cs file parameter model is null.
What am I doing wrong here? I've tried with and without JSON.stringify
this is in chtml razor page.
var Obj_A = [];
var obj = {};
var inputs = $("#fieldset1 input[name^=show_all_]");
for(var i = 0; i < inputs.length; i++){
var text_id = $(inputs[i]).attr("id").replace('show_all_','');
var value = $(inputs[i]).val();
obj[text_id]=value;
}
Obj_A.push(obj);
.
.
same for Obj_B
.
var model = {
Item_1: Obj_A ,
Item_2: Obj_B
};
$("#btn_insert").click(function () {
$.ajax({
type: "POST",
url: "/Home/Edit?handler=Import",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(model),
contentType: "application/json",
success: function (response) {
},
error: function (e) {
}
});
});
console.log for model has values.
this is in chtml.cs razor page.
public async Task<JsonResult> OnPostImport([FromBody]All_Obj model)
{
{
return new JsonResult(new { message = "2", filename = "1" });
}
}
model parameter is always null.
model class
public class model
{
public Item_1 field_1 { get; set; }
public Item_2 field_2 { get; set; }
}
Item_1 class
public class Item_1
{
public string field_item_1_1 { get; set; }
public string field_item_1_2 { get; set; }
public string field_item_1_3 { get; set; }
}
Item_2 class
public class Item_2
{
public string field_item_2_1 { get; set; }
public string field_item_2_2 { get; set; }
public string field_item_2_3 { get; set; }
}
Please use the following code to add data to model:
var Obj_A = {};
Obj_A.field_item_1_1=$("#show_all_field_item_1_1").val();
Obj_A.field_item_1_2=$("#show_all_field_item_1_2").val();
Obj_A.field_item_1_3=$("#show_all_field_item_1_3").val();
var Obj_B = {};
Obj_B.field_item_2_1=$("#show_all_field_item_2_1").val();
Obj_B.field_item_2_2=$("#show_all_field_item_2_2").val();
Obj_B.field_item_2_3=$("#show_all_field_item_2_3").val();
So that the model structure will be like this:
i have controller like this:
public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry)
{
//something
}
and model :
public class DTO_WorkOrder
{
public string Id { get; set; }
public string WoNo { get; set; }
public string ReqNo { get; set; }
public string ReqSparepartDate { get; set; }
public List<DTO_PartsWO> PartsList { get; set; }
}
this is my javascript to pass data to controller:
function SaveWorkOrder()
{
debugger;
var dd = $('#tbParts').DataTable().rows().data().toArray();
var vDataDet = new Array();
//Loop through the Table rows and build a JSON array.
$.each(dd, function (i, value) {
debugger;
var dataDetail = {};
dataDetail.Line = i;
dataDetail.PartCode = value[1];
dataDetail.PartDesc = value[2];
vDataDet.push(dataDetail);
debugger;
});
var tmp = $('#WorkOrderForm').serialize();
$.ajax({
type: 'POST',
url: '/Transactions/WorkOrder/SaveWorkOrder',
data: JSON.stringify({ objWork: tmp, listTry: vDataDet}),
success: function (mdl)
{
debugger;
},
error: function (mdl)
{
debugger;
}
)}
}
the codes pass the serialize form but not the list, my list null...
please help, already code for 3 days to pass both list and serialize form but not worked
I don't know if this is the right way, but it is working fine, instead using serialize, serializeArray work good so I can add list parameter in form, so this is the code I use:
function SaveWorkOrder()
{
debugger;
var dd = $('#tbParts').DataTable().rows().data().toArray();
var vDataDet = new Array();
// step 1 serialize array the form
var data = $("#WorkOrderForm").serializeArray();
//Loop through the Table rows and build a JSON array.
$.each(dd, function (i, value) {
debugger;
data[data.length] = { name: "PartsList[" + i + "].Line", value: i };
data[data.length] = { name: "PartsList[" + i + "].PartCode", value: value[1] };
data[data.length] = { name: "PartsList[" + i + "].PartName", value: value[2] };
debugger;
});
$.ajax({
type: 'POST',
url: '/Transactions/WorkOrder/SaveWorkOrder',
data: data,
success: function (mdl)
{
debugger;
},
error: function (mdl)
{
debugger;
}
})
}
This is the controller:
public ActionResult SaveWorkOrder(DTO_WorkOrder objWork)
{
//something
}
This is the models:
public class DTO_WorkOrder
{
public string Id { get; set; }
public string WoNo { get; set; }
public string ReqNo { get; set; }
public string ReqSparepartDate { get; set; }
public List<DTO_PartsWO> PartsList { get; set; }
}
public class DTO_PartsWO
{
public string WoNo { get; set; }
public Int32 Line { get; set; }
public string PartCode { get; set; }
public string PartName { get; set; }
}
you can see the result in pictureList in Object and detail List.
I need to change the value of a variable when a button is clicked. For that I made a function that updates the database using ajax. Here is what I have so far:
function atualizaBD(novoEstado) {
$.ajax
({
url:`/api/IgnicoesAPI/${id}`,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
Id : id,
Estado: novoEstado
}),
success: function (result) {
alert(result);
},
error: function () {
alert("ocorreu um erro!")
}
});
}
I have a variable called Estado and I want to change the value of that variable to a new one, novoEstado.
Here is my controller:
[HttpPut("{id}")]
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao, string novoEstado)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicao.Id)
{
return BadRequest();
}
var ig = _context.Ignicoes.FirstOrDefault (ignicaoId => ignicaoId.Id.Equals(id));
ig.Estado = novoEstado;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
Right now, everytime the function an error occurs alerting "ocorreu um erro"
Here is my Model:
public class Ignicoes
{
public Ignicoes()
{
ListaOcorrencias = new HashSet<Ocorrencias>();
}
[Key]
public int Id { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
//estado(recusada, aceite, em avaliacao, concluido)
public string Estado { get; set; }
public DateTime DataInicioPropostaIgnicao { get; set; }
public DateTime DataDecisaoIgnicao { get; set; }
//lista de ocorrencias
public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }
}
}
I generate the js object, which looks as follows:
cartStorage = {
name: 'testcustomer',
email: 'test#gmail.com',
items: [
{
licenseName: 'Private',
licensePrice: 2
},
{
licenseName: 'Public',
licensePrice: 4
}
],
totalPrice: 6
}
Then I pass this object to mvc controller using ajax
$.ajax({
url: '/TestPayment/ChargeTest',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(cartStorage),
success: function(response){
if (response != null) {
alert(response);
} else {
alert("Something went wrong");
}
}
});
Here's the viewmodel associated with this method
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public Items Items { get; set; }
}
}
Here's the mvc controller method, which processes the ajax request
[HttpPost]
public ContentResult ChargeTest([FromBody] PayerInfo model)
{
String FullName = model.name;
}
But when the server executes the controller method, the model turns out to be null.
However, if I comment out the Items class and the instance creation in the PayerInfo class in the viewmodel, then the model is being forwarded successfully and all the data is stored, I'm just having the problem with the list inside of js object.
What am I doing wrong?
items in your json object is a list. So you need to change the type of Items in your c# model to a list.
namespace Web.ViewModels.Payment
{
public class Items
{
public string licenseName { get; set; }
public int licensePrice { get; set; }
}
public class PayerInfo
{
public int totalPrice { get; set; }
public string name { get; set; }
public string email { get; set; }
public List<Items> Items { get; set; }
}
}
I have some problem while getting the object from the controller via AJAX call.To be precise, I would like to get the object which contains property with IEnumerable type.
Class 1 :
public class ChartItem
{
public string cName { get; set; }
public string label { get; set; }
public decimal value { get; set; }
public decimal value2 { get; set; }
public string value2Cur { get; set; }
public string value2Unit { get; set; }
public string color { get; set; }
public string strokeColor { get; set; }
public string chartTitle { get; set; }
}
Class 2 :
public class ReportParameter
{
public string ReportName { get; set; }
public string DateFrom { get; set; }
public string DateTo { get; set; }
public string CountryId { get; set; }
public string RegionId { get; set; }
public string RepresentativeId { get; set; }
public string CustomerId { get; set; }
public ExportFormatType ReportFormat { get; set; }
public EReport.ChartType ChartType { get; set; }
public bool EmailFlag { get; set; }
public IEnumerable<ChartItem> chartItems { get; set; }
}
This is the controller that execute the call :
[HttpPost]
public JsonResult ReloadReportSummary(EReport.ReportParameter rptParam)
{
EMAP.WEB_Bootstrap.Helper.ViewHelper viewHelper = new ViewHelper();
IEnumerable<EReport.ChartItem> resultChart=null;
try
{
EReport.ReportParameter eRpt = new EReport.ReportParameter();
eRpt.ReportName = ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName)).ToString();
switch ((EReport.ReportName)Enum.Parse(typeof(EReport.ReportName), rptParam.ReportName))
{
case EReport.ReportName.CRPotentialCustomerList:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count()};
break;
case EReport.ReportName.CRCustomerProductAppMasterPivot:
//reload the chart data
resultChart =
from cp in db.CustomerProducts
join pr in db.Products on cp.ProductID equals pr.ProductID
group cp by cp.Product.ProductDescription into grp
select new EReport.ChartItem { label = grp.Key, value = grp.Count() };
break;
default:
break;
}
eRpt.chartItems = resultChart;
---EDITED----
var result = eRpt;
return Json(new { Result = "OK", Record = result },
JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR"});
}
}
And this is the AJAX call :
$.ajax({
url: urlReportSummary,
data: JSON.stringify(rptParam),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
var len = result.Record.chartItem.length;
},
error: function (ex) {
alert(ex);
}
});
Actually I would like to go through each Record.chartItem's object and do some process there. But somehow the returned record not being recognized. Below is the error :
"TypeError: result.Record.chartItem is undefined".
May I know what is the correct way to get the list of data using AJAX ?
Thanks a lot
Change the success function as below and try
success: function (result) {
var len = result.Record.chartItems.length;
},
You have misspelled the property chartItems. I think now it will work