angularjs send nested object to API - javascript

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;
}

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

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. :)

KendoUI treeview children are displayed as undefined

I have a treeview in kendoUI in which main nodes are calling into an mvc controller and that controller looks to whether there is an nullable id passed in and then uses a different model.
What I hit the url : http://localhost:2949/Report/GetReportGroupAssignments
I see this JSON
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4}
]
Now my mvc controller looks like this
public JsonResult GetReportGroupAssignments(int? id)
{
var model = new List<ReportGroup>();
var defModel = new List<ReportDefinition>();
try
{
if (id == null)
{
model = _reportService.GetReportGroups("en-us").ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
defModel = _reportService.GetReportDefinitions().Where(e=>e.ReportGroupID ==Convert.ToInt32(id)).ToList();
return Json(defModel, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error loading LoadReportList.");
return null;
}
}
My Kendo javascript looks like the following:
var serviceRoot = "/Report"; // "//demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments", //"/LoadReportTree", // "/Employees",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,hasChildren: "Id"
}
}
});
var treeview = $("#treeview").kendoTreeView({
expanded: true,
dragAndDrop: true,
dataSource: homogeneous,
dataTextField: "ReportGroupName"
}).data("kendoTreeView");
Seems that the calls (which I discovered that children records have a "load" method that it called behind the seens, so basically I pass in the ID in order to get the data from the other model ( table in db)
(Id is mapped with automapper to ReportGroupID )
So when i click to the left of "Standard Rports" I am getting all of these children as undefined, How do I get these to show up properly?
Update: My ReportDefinition class:
public class ReportDefinition {
public override int Id { get; set; }
public string ReportKey { get; set; }
public string ReportName { get; set; }
public int? ReportNameResID { get; set; }
public string ReportDef { get; set; }
public int? ReportDefinitionResID { get; set; }
public string ReportAssembly { get; set; }
public string ReportClass { get; set; }
public int ReportGroupID { get; set; }
public int AppID { get; set; }
public int SortOrder { get; set; }
public bool IsSubReport { get; set; }
}
I think your problem is that the class ReportDefinition does not have a property called: ReportGroupName. That is why TreeView displays 'undefined'.
Try adding this Property to your ReportDefinition class like:
public class ReportDefinition {
// Other Properties
// I guess this property is missing
public string ReportGroupName { get; set; }
}

Read JSON with Angular

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>

What does [ ] mean in javascript and how to return it from C#

I returned class from C# to javascript in this format
Format needed in javascript:
{ key: 1, label: 'Food'}
This part works and the class I used to return from C# looks like this:
public static FoodClass get_AllFood()
{
FoodClass FoodClass = new FoodClass
{
label = "Food",
key = "1",
};
return FoodClass;
}
public class FoodClass
{
public FoodClass() { }
public FoodClass(string data1, string data2)
{
label = data1;
key = data2;
}
public string label { get; set; }
public string key { get; set; }
public Boolean open { get; set; }
public int ID { get; set; }
}
Now when I have to add a child element to my format, It has the [ ] bracket which I dont know how to get from C#
Format needed in javascript:
{ key: 1, label: 'Food', open: false, children: [{ key: 211, label: 'Burger' }]}
That is an array - in this case, with one element. Most json serializers will accept a list or array for that, so:
public List<Child> children {get;set;}
or
public Child[] children {get;set;}
where Child is something like:
public class Child {
public int key {get;set;}
public string label {get;set;}
}
You can rename Child to whatever makes sense without it impacting anything.

Categories

Resources