Iterate over JSON object and gather model values - javascript

I am trying to send an ajax get request to receive all of the entries in one of my tables in the database as a JSON object.
After retrieving this, I am trying to iterate over all of the objects and compare the objects ID, to a local ID.
If there is a match, I want to set some html text boxes to their values, but I can't get it to work.
JavaScript:
$.ajax({
url: "/Home/AllEvents",
data: calEvent.id,
dataType: "json",
success: function(response) {
for (var i = 0; i < response.length; i++) {
var obj = response[i];
if (obj.ID == calEvent.id)
{
document.getElementById('updateID').value = obj.ID;
document.getElementById('updateType').value = obj.EventType;
document.getElementById('updateDuration').value = obj.Hours;
break;
}
}
},
AllEvents:
public JsonResult AllEvents(double? start, double? end)
{
var eventList = new List<object>();
foreach (Event ev in db.Events)
{
eventList.Add(ev);
}
return Json(eventList.ToArray(), JsonRequestBehavior.AllowGet);
}
Event Model:
public int ID { get; set; }
[Required]
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required]
[EnumDataType(typeof(EventType), ErrorMessage = "Submitted value is not valid.")]
[Display(Name = "Type")]
public EventType? EventType { get; set; }
[Required]
public double Hours { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Person Person { get; set; }
Any help is greatly appreciated.

With the help of Stephen, I managed to get this working with the following:
FindEvent:
public JsonResult FindEvent(int ID)
{
Event ev = db.Events.Where(e => e.ID == ID).FirstOrDefault();
object eventObject = new
{
hours = ev.Hours.ToString(),
eventType = ev.EventType.ToString()
};
return Json(eventObject, JsonRequestBehavior.AllowGet);
}
JavaScript:
$.ajax({
url: '#Url.Action("FindEvent", "Event")',
data: { ID: calEvent.id },
dataType: "json",
success: function (response) {
console.log(response);
document.getElementById('updateID').value = calEvent.id;
document.getElementById('updateType').value = response.eventType;
document.getElementById('updateDuration').value = response.hours;
},
error: function() {
// Handle error
}
});

Related

Pass multiple json objects throught ajax to razor pages

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:

Passing Form Serialize and list to controller is not working?

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.

ASP.Net Core 3 Posting JSON array to controller

I´m having issues passing an array of JSON objects to an MVC controller in ASP.Net core 3. The JSON object is built from a CSV file and passed through an AJAX call. The correct action is called but the object received is always null.
JS:
async function updateData(){
var obj = await getData();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/admin/metric/Update",
data: obj,
dataType: 'json',
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
async function getData(){
var metric = {};
var metrics = [];
var response = await fetch('https://bloburi.net/source/file.csv');
var data = await response.text();
var table = data.split('\n').slice(1);
table.forEach(row => {
var columns = row.split(',');
metric["FirstName"] = columns[0];
metric["LastName"] = columns[1];
metric["Email"] = columns[2];
metric["AverageHandleTime"] = columns[3];
metric["AverageFollowUp"] = columns[4];
metric["AverageHold"] = columns[5];
metric["Date"] = columns[6];
metrics.push(JSON.stringify(metric));
});
console.log(metrics);
return metrics;
}
Models:
public class MetricBase
{
[Required]
public string Date { get; set; }
public double AverageHandleTime { get; set; }
public double AverageHold { get; set; }
public double AverageFollowUp { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MetricModel
{
public IEnumerable<MetricBase> MetricBase { get; set; }
}
Controller:
[HttpPost]
public IActionResult Update([FromBody]MetricModel obj)
{
return Json(new { obj });
}
I think the issue may be on how I'm deffining the class that is receiving the JSON, but I've tried multiple things like deffining MetricBase as a List<> or straight up as an array in MetricModel, but it doesn't seem to work.
Any help is appreciated!
You adding the stringify item inside array via code
metrics.push(JSON.stringify(metric));
instead of stringify the whole array. Change the line to
metrics.push(metric);
and data: obj, to
data: JSON.stringify(obj),.
With the mentioned change, the $.ajax sends the whole array. Also change the action to
public IActionResult Update([FromBody]IEnumerable<MetricBase> obj)

MVC6 Assign a viewmodel list property to a javascript variable

I have a viewmodel with the following property:
public class CompanyDetailsViewModel
{
[Required(ErrorMessage = "A Company Name is required")]
[Display(Name = "Company Name:")]
[StringLength(100)]
public string CompanyName { get; set; }
...
public IList<SuburbAndPostcode> SuburbAndPostcodesList { get; set; }
}
The list was created from this POCO class:
public class SuburbAndPostcode
{
[Key]
public int SuburbsAndPostcodesId { get; set; }
public string Suburb { get; set; }
public string PostCode { get; set; }
public State State { get; set; }
}
This is the state object:
public class State
{
[Key]
public int StateId { get; set; }
public string ShortName { get; set; }
public string Name { get; set; }
public virtual ICollection<CompanyDetail> CompanyDetails { get; set; }
}
I am trying to create a variable with the suburb and postcode properties as a list that I can use for an autocomplete function however I cant seem to assign the Model.SuburbsAndPostCodesList to a variable.
I have tried various javascript options indicated from other questions on this forum like here.
I would like to have a javascript variable that represents the list and I have tried just setting:
var suburbs = #Model.SuburbAndPostcodesList
I've tried using json and I have tried looping through the Model but get an error saying that the variable "test" is out of context:
var test =[];
#for (int i = 0; i < Model.SuburbAndPostcodesList.Count; i++)
{
test[i]=...
}
I have also tried using "push" and ".Encode".
I would like to know how to assign this list of strings and state object to a javascript variable?
Use Ajax Call to achieve Auto-complete functionality
$(document).ready(function () {
$("#txtPostcodes").keyup(function () {
//AutoComplete the Results
$("#txtPostcodes").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../ControllerName/ActionName",
data: "{'input':'" + document.getElementById('txtPostcodes').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {
var suburbs = data;
}
},
error: function (result) {
}
});
}
});
}
});
});
In the end I simply equated the various members of the viewmodel list and build up a javascript multi dimensional array for the autocomplete function. Here it is:
var suburbs = [
#for (var i = 0; i < Model.SuburbAndPostcodesList.Count; i++) {
<text>{
id: "#Model.SuburbAndPostcodesList[i].SuburbsAndPostcodesId",
suburb: "#Model.SuburbAndPostcodesList[i].Suburb",
postCode: "#Model.SuburbAndPostcodesList[i].PostCode",
state: "#Model.SuburbAndPostcodesList[i].State.ShortName"
}#(i == Model.SuburbAndPostcodesList.Count - 1 ? "" : ",")</text>
}
];
$("#Suburb").autocomplete({
source: function (req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
var a = $.grep(suburbs, function (item, index) {
return matcher.test(item.suburb);
});
a = $.map(a, function (x) {
return {
label: x.suburb + " - " + x.postCode,
value: x.suburb,
suburbDetails: x
};
});
responseFn(a);
},
select: function (value, data) {
if (typeof data == "undefined") {
} else {
$("#Postcode").val(data.item.suburbDetails.postCode);
}
},
change: function (event, ui) {
if (!ui.item) {
$("#Suburb").val("");
$("#Postcode").val("");
}
}
});

How to Save an id for a dropdownlist using angular js?

I have a problem in my project using Angularjs. Here is my code:
Controller
// GET: api/CustomerLists/5
[ResponseType(typeof(CustomerList))]
public IHttpActionResult GetCustomerList(int id)
{
var data = (from cust in db.CustomerLists
join call24 in db.CallingList4
on cust.CustID equals call24.CustID
where cust.CustID == id
select new CustomerVM
{
CustID = cust.CustID,
Customer = cust.Customer,
Call4ID = call24.Call4ID,
Wk1WebID = call24.Wk1WebID,
Wk1OrdID = call24.Wk1OrdID
}).First();
return Ok(data);
}
// PUT: api/CustomerLists/5
[ResponseType(typeof(void))]
public IHttpActionResult PutCustomerList(CustomerVM vm)
{
if (ModelState.IsValid)
{
var cust = db.CustomerLists.Find(vm.CustID);
var call4 = db.CallingList4.Find(vm.Call4ID);
cust.Customer = vm.Customer;
cust.ContactName = vm.ContactName;
call4.Wk1OrdID = vm.Wk1OrdID;
call4.Wk1WebID = vm.Wk1WebID;
db.CustomerLists.Attach(cust);
db.Entry(cust).State = EntityState.Modified;
db.CallingList4.Attach(call4);
db.Entry(call4).State = EntityState.Modified;
db.SaveChanges();
}
return StatusCode(HttpStatusCode.NoContent);
}
JS
var EditCtrl = function ($scope, $routeParams, $location, data, $http) {
var id = $routeParams.editId;
$scope.lis = data.get({ id: id });
$scope.selectTest = null;
$scope.testTest = [];
$http({
method: 'GET',
url: '/api/OrderStatus/',
data: { OrderStatID: 1 }
}).success(function(result) {
$scope.testTest = result;
});
$scope.selectTest1 = null;
$scope.testTest1 = [];
$http({
method: 'GET',
url: '/api/WebStatus/',
data: { WebStatID: 1 }
}).success(function (result1) {
$scope.testTest1 = result1;
});
$scope.save = function () {
data.update({ id: id }, $scope.lis, function () {
$location.path('/');
});
};
Template
<select class="form-control" ng-model="selectTest" ng-model="lis.OrderStatID">
<option ng-repeat="s in testTest" value="{{s.OrderStatID}}">{{s.OrderStatus}}</option>
</select>
View Model
public class CustomerVM
{
public int CustID { get; set; }
public string Customer { get; set; }
public int? Priority { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
public int Call4ID { get; set; }
public int? Wk1WebID { get; set; }
public int? Wk1OrdID { get; set; }
public int? OrderStatId { get; set; }
public string OrderStatus { get; set; }
}
}
When I try to update, the CustomerList details update just fine, but the CallingList4 details return null when I select a status and I try to save an ID. How do I save the ID from another table to the main table which is callingList24? please help
UPDATED
look at this screen shot it does select from the table, but the problem it does not want to save an id to another table.
I see it is a design issue rather than code issue
You need to redesign your ViewModel to include subclasses for properties like Status and CallingList
Then pass the value using expression like {{s.Status.ID}} and so on for all composed properites

Categories