Read JSON with Angular - javascript

Sorry if this is too simple, I am new to JSON and Angular.
So, I have a server response in JSON that I don't quite understand and I need to read using AngularJS. This is the JSON.
{
"$id": "1",
"$values":
[
{
"$id": "2",
"ID": 2,
"FiscalYear": "",
"Month": 1,
"Day": 1,
"Surname": "test",
"FirstName": "test",
"Program": "smart",
"PoliceFileNumber": "123",
"CourtFileNumber": 123,
"Service": "1",
"VictimOfIncident": "yes",
"FamilyVoilenceFile": "123",
"Gender": "M",
"Ethnicity": "1",
"Age": "22",
"AssignedWorker": 1,
"StatusOfFile": 1
}
]
}
This represent a query from a table in my database.
1) What I don't understand is why it's included the id and values at the beginning?
2) How do I access the variables inside values? For example, how do read the Month value?
In the server I have this:
public class ClientDTOesController : ApiController
{
private LookupContext db = new LookupContext();
// GET: api/ClientDTOes
public IQueryable<ClientDTO> GetClientsDTO()
{
return db.ClientsDTO;
}
And this is my model:
public partial class ClientDTO
{
public int ID { get; set; }
public String FiscalYear { get; set; }
public int Month { get; set; }
public int Day { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public String Program { get; set; }
public string PoliceFileNumber { get; set; }
public int CourtFileNumber { get; set; }
public String Service { get; set; }
public String VictimOfIncident { get; set; }
public String FamilyVoilenceFile { get; set; }
public string Gender { get; set; }
public String Ethnicity { get; set; }
public String Age { get; set; }
public int AssignedWorker { get; set; }
public int StatusOfFile { get; set; }
}
My Client code:
(function () {
// creates a module and register to the app
var app = angular.module('ReportViewer', []);
// controller declaration
var MainController = function ($scope, ReportService) {
// object model
var _Client = {
Age: "",
CourtFileNumber: "",
Day: "",
Ethnicity: "",
FamilyVoilenceFile: "",
FirstName: "",
FiscalYear: "",
Gender: "",
Month: "",
PoliceFileNumber: "",
Program: "",
Service: "",
Surname: "",
VictimOfIncident: ""
};
// GET ALL
var onGetAllComplete = function (data) {
$scope.clients = data;
};
var onGetAllError = function (reason) {
$scope.error = "Could not get all clients.";
};
// accessed from the view
// calls the service function
$scope.getClient = function () {
ReportService.getAllClients()
.then(onGetAllComplete, onGetAllError);
};
// exposes the 'object'
$scope.client = _Client;
};
//register the controller to the app
app.controller("MainController", MainController);
}());
And the service:
// ReportService.js
(function () {
var ReportService = function ($http) {
var baseUrl = 'http://localhost:16188/api/Report/ReportClient/1/1';
var _getAllClients = function () {
return $http.get(baseUrl)
.then(function (response) {
return response.data
});
};
return {
getAllClients: _getAllClients
};
};
var module = angular.module("ReportViewer");
module.factory("ReportService", ReportService);
}());
I am trying to display the values here:
<!DOCTYPE html>
<html data-ng-app="ReportViewer">
<head>
<title>Report</title>
<script src="../Scripts/AngularJS/angular.js"></script>
<script src="../Scripts/App/MainController.js"></script>
<script src="../Scripts/App/ReportService.js"></script>
</head>
<body data-ng-controller="MainController">
<div id="wrapper" class="container">
<div class="summary">
<h1>Worker summary & detail report</h1>
<button ng-click="getClient()">Get All Clients</button>
<div id="test" ng-show="clients" >
<p>{{client.courtFileNumber}}</p>
<p>{{client.Day}}</p>
<p>{{client.Ethnicity}}</p>
<p>{{client.FamilyVoilenceFile}}</p>
<p>{{client.FirstName}}</p>
<p>{{client.FiscalYear}}</p>
<p>{{client.Gender}}</p>
<p>{{client.Month}}</p>
<p>{{client.PoliceFileNumber}}</p>
<p>{{client.Program}}</p>
<p>{{client.Service}}</p>
<p>{{client.Surname}}</p>
<p>{{client.VictimOfIncident}}</p>
</div>
Thank you very much for any suggestions.

Your code looks perfect, basically problem is with you HTML, you could use ng-repeat which act as like for loop which will loop through all clients and show it.
Markup
<div id="test" ng-repeat="client in clients.$values">
<p>{{client.courtFileNumber}}</p>
<p>{{client.Day}}</p>
<p>{{client.Ethnicity}}</p>
<p>{{client.FamilyVoilenceFile}}</p>
<p>{{client.FirstName}}</p>
<p>{{client.FiscalYear}}</p>
<p>{{client.Gender}}</p>
<p>{{client.Month}}</p>
<p>{{client.PoliceFileNumber}}</p>
<p>{{client.Program}}</p>
<p>{{client.Service}}</p>
<p>{{client.Surname}}</p>
<p>{{client.VictimOfIncident}}</p>
</div>

Related

Can not get a value of key-value pair using [FromBody]

Data is sent from front-end to back-end. Request body is created like this
var stateWithValue = {};
for (const item in self.pricings()) {
state[item] = self.pricings()[item]["Comment"];
}
var request = {
generalComment: self.generalComment(),
stateWithValue: stateWithValue
};
Request body looks like this
{
generalComment: "test comment",
stateWithValue:
{
Delaware: "Value1",
California: "Value2",
Texas: "Value3"
}
}
Number of elements in stateWithValue can be different for every request.
In the back-end, data is taken using [FromBody] attribute
public WebApiResponseGeneric<EmptyResponse> State([FromBody] StateRequest request)
StateRequest.cs
public class StateRequest : PublicRequest
{
public string GlobalComment { get; set; }
public StateWithValue StateWithValue { get; set; }
}
public class StateWithValue
{
public string State { get; set; }
public string Value { get; set; }
}
In network tab(dev console) payload looks like this
generalComment: test general comment
stateWithValue[Delaware]: Value1
stateWithValue[California]: Value2
stateWithValue[Texas]: Value3
The Problem
In back-end request object, StateWithValue.State StateWithValue.Value are both null.
YOu have to post PublicRequest class too. But for your request body json, your class should be
public class StateRequest : PublicRequest
{
public string generalComment{ get; set; }
public Dictionary<string, string> stateWithValue { get; set; }
}
or change
public class StateRequest : PublicRequest
{
public string GlobalComment { get; set; }
public List<StateWithValue> StateWithValue { get; set; }
}
and javascript
var stateWithValue = [];
for (const item in self.pricings()) {
var stateWithValueItem={};
stateWithValueItem.State =item;
stateWithValueItem.Value = self.pricings()[item]["Comment"];
stateWithValue.push(stateWithValueItem);
}
In order to map the JSON:
{
generalComment: "test comment",
stateWithValue:
{
Delaware: "Value1",
California: "Value2",
Texas: "Value3"
}
}
You would need to use the following C# model
public class StateRequest : PublicRequest
{
public string GeneralComment { get; set; }
public StateWithValue StateWithValue { get; set; }
}
public class StateWithValue
{
public string Dalaware { get; set; }
public string California { get; set; }
public string Texas { get; set; }
}
If you want to map multiple states then consider using an array instead, something like:
{
generalComment: "test comment",
stateWithValue:
[
State: "Delaware", Value: "Value1",
State: "California", Value: "Value2",
State: "Texas", Value: "Value3"
]
}
But your model would need to be updated to look something like this:
public class StateRequest : PublicRequest
{
public string GeneralComment { get; set; }
public List<StateWithValue> StatesWithValues { get; set; }
}
Note: There is a typo with general vs Global in your sample code

angularjs send nested object to API

Hi I am developing angular with web API application. I am trying receive object with array from angular. Unfortunately I am receiving null in the array.
this.updateprocesswithtemplates = function () {
var sub = {
projectId: "50",
code: "app",
templates: {
title: "templatetiltle",
version: "templateversion",
visible: "templatevisible",
templatefileid: "31",
displayorder: "1"
}
};
var responseservice = $http.put('/api/processes/81/', sub).success(function (response) {});
return responseservice;
}
In web API i have below class
public class updatercvparams
{
public string projectId{ get; set; }
public int code { get; set; }
public templates[] templates { get; set; }
}
public class templates
{
public string title { get; set; }
public string version { get; set; }
public int displayorder { get; set; }
public string visibility { get; set; }
public int templatefileid { get; set; }
}
When I send above request object I will receive null in templates.
public HttpResponseMessage Put(int id, updatercvparams obj)
May I know, Am I missing anything here?
As you have defined templates as an array, you need to send an array not a object.
var sub = {
projectId: "50",
code: "app",
templates: [{
....
}]
};
As per your entity(class) in web api, field name should be same in javascript object. While you sending list of data like array, use square bracts('[]').
this.updateprocesswithtemplates = function() {
var sub = {
projectId: "50",
code: "app",
templates: [{
title: "templatetiltle",
version: "templateversion",
visibility: "templatevisible",
templatefileid: "31",
displayorder: "1"
}]
};
var responseservice = $http.put('/api/processes/81/', JSON.stringify(sub))
.success(function(response) {});
return responseservice;
}

Pass an Object from Angularjs to MVC controller and map to Class Object

I have an object in angularjs which I want to pass and map it to custom c# class in mvc controller. but whenever I am doing this class object is null completely.
$scope.Get = function () {
var EService = [{
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
}];
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
})
MVC Controller and Class:
[HttpPost]
public string Insert(ServicesMaster Service)
{
GIBCADBEntities gfientity = new GIBCADBEntities();
var record = "Sent"
return Json(record, JsonRequestBehavior.AllowGet);
} public class ServicesMaster
{
public string id { set; get; }
public string servicename { set; get; }
public string servicetype { set; get; }
public int? monthlyrental { set; get; }
public string serviceremarks { set; get; }
public byte servicestatus { set; get; }
public DateTime? activationdate { set; get; }
public DateTime? deactivationdate { set; get; }
}
The javascript variable/object "EService" is ok here, and when passing only the ServicesMaster object is created with null values and no data is mapped to it. I can send single string or any value from here but when sending a complete object its behaving like this.
You are passing an array from front end and fetching object from server end. just remove the "[" and "]" brace while set value to EService . Like :
$scope.Get = function () {
var Service = {};
Service = {
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
};
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
});
};
It should work now. :)

KnockoutJS with MVC, Model and functions

I am working on a project which includes MVC and KnockoutJS. As this is the first time i'm working with KnockoutJS i'm running into a lot of issues.
I want to put my MVC Viewmodel on the webpage in a tabbed interface. Then from that interface i want to call functions depending on which button i press.
Currently i am getting the model to load and show itself fine, but i cannot call any functions i am trying to create.
Also i have no clue that the way i am creating this at the moment is the correct one.
I have the following model:
public partial class SSoSearchModel
{
public string SearchParameter { get; set; }
public string SearchValue { get; set; }
public string SearchLabel { get; set; }
public IQueryable<SsoRecordResultViewModel> searchResults { get; set; }
public List<SelectListItem> ParameterList { get; set; }
public List<SelectListItem> LabelList { get; set; }
}
The SearchResults look like this
public partial class SsoRecordResultViewModel
{
[JsonProperty(PropertyName = "first_name")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "last_name")]
public string LastName { get; set; }
[JsonProperty(PropertyName = "email_address"), DefaultValue(PropertyName = "email_addresses")]
public string EmailAddress { get; set; }
[JsonProperty(PropertyName = "phone_number"), DefaultValue(PropertyName = "phone_numbers")]
public string PhoneNumber { get; set; }
[JsonProperty(PropertyName = "Klantnummer"), CustomAttribute(PropertyName = "Klantnummer")]
public string Klantnummer { get; set; }
[JsonProperty(PropertyName = "verzekerdenummer"), CustomAttribute(PropertyName = "Verzekerdennummer")]
public string Verzekerdenummer { get; set; }
[JsonProperty(PropertyName = "person_id")]
public string SSOID { get; set; }
[JsonProperty(PropertyName = "initials")]
public string Initialen { get; set; }
}
And this is all loaded in the Index function of the controller with dummy data
public ActionResult Index()
{
List<SsoRecordResultViewModel> temp = new List<SsoRecordResultViewModel>();
temp.Add(new SsoRecordResultViewModel { SSOID = "ea373d27-142d-48f6-86c9-dcdb15e316d2", EmailAddress = "A", FirstName = "a", Klantnummer = "1", Verzekerdenummer = "1", PhoneNumber = "1", Initialen = "A", LastName = "a" });
temp.Add(new SsoRecordResultViewModel { SSOID = "2d613aba-3f89-43b0-919a-1aa615086ff3", EmailAddress = "b", FirstName = "b", Klantnummer = "2", Verzekerdenummer = "2", PhoneNumber = "2", Initialen = "b", LastName = "b" });
temp.Add(new SsoRecordResultViewModel { SSOID = "c142f22e-7664-4a9c-9303-293b48acbf65", EmailAddress = "c", FirstName = "c", Klantnummer = "3", Verzekerdenummer = "3", PhoneNumber = "3", Initialen = "c", LastName = "c" });
SSoSearchModel model = new SSoSearchModel();
model.searchResults = temp.AsQueryable(); //Enumerable.Empty<SsoRecordResultViewModel>().AsQueryable();
//zoekopties
model.ParameterList = new List<SelectListItem>();
model.ParameterList.Add(new SelectListItem { Text = "Zoek op Klantnummer", Value = "Klantnummer" });
model.ParameterList.Add(new SelectListItem { Text = "Zoek op Verzekerdenummer", Value = "Verzekerdenummer" });
model.ParameterList.Add(new SelectListItem { Text = "Zoek op E-mail adres", Value = "Email" });
model.ParameterList.Add(new SelectListItem { Text = "Zoek op SSO ID", Value = "SSOID" });
model.ParameterList.Add(new SelectListItem { Text = "Zoek op Telefoonnummer", Value = "Telefoonnummer" });
//Labels
model.LabelList = new List<SelectListItem>();
model.LabelList.Add(new SelectListItem { Text = "Rel1", Value = "Rel1" });
model.LabelList.Add(new SelectListItem { Text = "Rel2", Value = "Rel2" });
return View(model);
}
Now on the Index.cshtml i offcourse have my markup which shows the data great at the moment, but the KnockoutJS is the issue.
The javascript looks the following:
<script>
function ViewModel() {
var self = this;
self.Search = ko.observableArray(searchResults);
self.save = function(ssoid){
//ajax hier
};
};
var rawData = #Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var Data = ko.mapping.fromJS(rawData,ViewModel);
ko.applyBindings(Data);
</script>
This currently shows me the data, but i do not know how i can call the save function. I have this but this does not work:
<button type="button" class="btn btn-default" aria-label="Bewaren" data-toggle="tooltip" data-placement="top" title="Bewaar de gegevens" data-bind="click: function() { $data.save(SSOID()); }"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span></button>
Also when i swap the values in ko.mapping.fromJS(rawData,ViewModel); the data does not get shown anymore.
Anyone here who can help me with this as it is driving me crazy.

Binding a multi dimentional javascript array as method parameter in c#

hi i am looking for a way to bind this data :
columns[0][data]:0
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:1
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:2
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
columns[3][data]:3
columns[3][name]:
columns[3][searchable]:true
columns[3][orderable]:true
columns[3][search][value]:
columns[3][search][regex]:false
columns[4][data]:4
columns[4][name]:
columns[4][searchable]:true
columns[4][orderable]:true
columns[4][search][value]:
columns[4][search][regex]:false
columns[5][data]:5
columns[5][name]:
columns[5][searchable]:true
columns[5][orderable]:true
columns[5][search][value]:
columns[5][search][regex]:false
columns[6][data]:6
columns[6][name]:
columns[6][searchable]:true
columns[6][orderable]:true
columns[6][search][value]:
columns[6][search][regex]:false
columns[7][data]:7
columns[7][name]:
columns[7][searchable]:true
columns[7][orderable]:true
columns[7][search][value]:
columns[7][search][regex]:false
columns[8][data]:8
columns[8][name]:
columns[8][searchable]:true
columns[8][orderable]:false
columns[8][search][value]:
columns[8][search][regex]:false
to my method so far i tried an object array but it didn't work here is my method definition:
public async Task<JsonResult> DriveDataTable(jQueryDataTableParamModel param)
and jQueryDataTableParamModel class :
public class jQueryDataTableParamModel
{
//Paging first record indicator. This is the start point in the current data set (0 index based - i.e. 0 is the first record).
public int start { get; set; }
// global search keyword
public string search { get; set; }
// Number of records that should be shown in table
public int length { get; set; }
//represent the index of column which is to ordered
public int orderByCol { get; set; }
//order direction (asc or desc)
public string orderDirection { get; set; }
public object[] columns { get; set; }
}
Assuming that myArr is your javascript multidimensional array you can npass it to c# in this way
JSON.stringify(myArr)
then in c# class you can change the property in
public object columns { get; set; }
but I think that also
public string columns { get; set; } should work
then server side you could deserialize it in some way
Usually I send serialized objects over javascript and when they come back in a string format to my C# methods I deserialize them in this way
[HttpPost]
public ActionResult MyMethod(string model)
{
//model in this case is what JSON.stringify(myArr) sends
var jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var deserializedModel = JsonConvert.DeserializeObject<MyComplexType>(model, jsSettings);
//now deserializedModel is of type MyComplexType
return PartialView("~/Views/Shared/Somefile.cshtml", deserializedModel);
}
Additional Information.
Here Is classes
public class JQDTParams
{
public int draw { get; set; }
public int start { get; set; }
public int length { get; set; }
public JQDTColumnSearch /*Dictionary<string, string>*/ search { get; set; }
public List<JQDTColumnOrder/*Dictionary<string, string>*/> order { get; set; }
public List<JQDTColumn/*Dictionary<string, string>*/> columns { get; set; }
}
public enum JQDTColumnOrderDirection
{
asc, desc
}
public class JQDTColumnOrder
{
public int column { get; set; }
public JQDTColumnOrderDirection dir { get; set; }
}
public class JQDTColumnSearch
{
public string value { get; set; }
public string regex { get; set; }
}
public class JQDTColumn
{
public string data { get; set; }
public string name { get; set; }
public Boolean searchable { get; set; }
public Boolean orderable { get; set; }
public JQDTColumnSearch search { get; set; }
}
And Usage
HTML
<div>
<table id="aractipiListesi" class="display" cellspacing="0" width="100%">
<thead>
<tr class="filter-input">
<th>PK</th>
<th>Markası</th>
<th>Modeli</th>
<th></th>
</tr>
<tr>
<th>PK</th>
<th>Markası</th>
<th>Modeli</th>
<th></th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#aractipiListesi').DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"pageLength": 8,
"columns": [
{
"name": "ID",
"orderable": false
},
{
"name": "MARKAADI",
"orderable": true
},
{
"name": "TIPADI",
"orderable": true
},
{
"name": "SEC",
"orderable": false
}
],
"ajax":
{
url: "#Url.Action("AracTipiAra", "Common", new { area = "" })",
type: "post"
},
"columnDefs":
[
{
"render": function (data, type, row) { return AracTipiListesiTableDropDownToggle(data, type, row); },
"targets": [3]
},
{
"visible": false,
"targets": [0]
}
],
"language": DTConstants.Language
});
var aractipi_filtrelenecekBasliklar = ['Markası', 'Modeli'];
// Setup - add a text input to each footer cell
$('#aractipiListesi thead .filter-input th').each(function () {
var title = $(this).text();
if (title != '' && $.inArray(title, aractipi_filtrelenecekBasliklar) >= 0) {
$(this).html('<input type="text" placeholder="' + title + ' Ara" />');
}
});
// DataTable
var table = $('#aractipiListesi').DataTable();
// Apply the search
table.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
});
</script>
</div>
Controller
public JsonResult AracTipiAra(JQDTParams param)
{
using (var db = new MBOSSEntities())
{
var q = from x in db.VW_ARACMARKATIPI select x;
var nonfilteredcount = q.Count();
//filter
//-------------------------------------------------------------------
foreach (var item in param.columns)
{
var filterText = item.search.value;
if (!String.IsNullOrEmpty(filterText))
{
filterText = filterText.ToLower();
switch (item.name)
{
case "MARKAADI":
q = q.Where(
x =>
x.MARKAADI.ToLower().Contains(filterText)
);
break;
case "TIPADI":
q = q.Where(
x =>
x.TIPADI.ToLower().Contains(filterText)
);
break;
}
}
}
//order
//-------------------------------------------------------------------
foreach (var item in param.order)
{
string orderingFunction = "MARKAADI";
switch (item.column)
{
case 1: orderingFunction = "MARKAADI";
break;
case 2: orderingFunction = "TIPADI";
break;
}
q = OrderClass.OrderBy<VW_ARACMARKATIPI>(q, orderingFunction, item.dir.GetStringValue());
}
//result
//-------------------------------------------------------------------
var filteredCount = q.Count();
q = q.Skip(param.start).Take(param.length);
var data = q.ToList()
.Select(r => new[] {
r.ARACMARKAPK.ToString(),
r.MARKAADI,
r.TIPADI,
}
);
return Json(new
{
draw = param.draw,
recordsTotal = nonfilteredcount,
recordsFiltered = filteredCount,
data = data
}, JsonRequestBehavior.AllowGet);
}
}

Categories

Resources