How to send ajax post array to mvc controller in vb.net - arrays

My javascript code;
<script>
$(document).on('click', '.Send', function () {
var a = [];
$(".k_sure").each(function () {
var a_array= a.push($(this).val());
});
var b= [];
$(".k_sure").each(function () {
var b_array= a.push($(this).val());
});
var DataDiscount= { time: a_array, ind: b_array};
$.ajax({
type: "POST",
url: "/admin/pan/discount",
data: DataDiscount,
traditional: true,
dataType: 'html',
success: function (c) { }
error: function () { }
});
});
</script>
My array;
DataDiscount:{time:["5","8","9"], ind:["%10","%15","%20"]}
my controller code;
Function discount(time As String, ind As String) As String
Dim x_add As New Discounts
If x_add IsNot Nothing Then
x_add.time = time
x_add.ind = ind
db.Discounts.Add(x_add)
db.SaveChanges()
Return "Success"
Else
Return "Err"
End If
Return ""
End Function
but only records the first data (5 and %10)
how to fix Controller code. My english is bad so sorry

I don't know about your controller settings but you should send your data as a JSON object.
Try to JSON.stringify your data:
var DataDiscount= JSON.stringify({ time: a_array, ind: b_array});

Related

How to send an object and array through Angularjs service

I am trying to send an object and array in the same time to an API, but i got an error
This is the object (from input boxes)
var vacation = {
Vac_Main_Key: $scope.vackey, Vac_Main_Code: $scope.code, Gender_Type: $scope.gen, CareeService_Flag: $scope.career, Vac_Duration: $scope.vduration,
Duration_Flag: $scope.vflag}
This is the array (from multiple check boxes)
$scope.selectedcontract = function (con)
{
if (con.details == true) {
$scope.vacationcontracts.push({ VacMKey: $scope.vackey, WType: con.sys_key });
console.log($scope.vacationcontracts);
}
else if (con.details == false) {
$scope.vacationcontracts.splice(con, 1);
}
}
The save button
var promisePost = vacationsetupSrv.save(vacation, $scope.vacationcontracts);
promisePost.then(function () {}
The angularjs service:
var vacationsetup = angular.module("vacationsetup", [])
.service("vacationsetupSrv", function ($http) {
var urlBase = "/VacationSetupAPI/api";
this.save = function (url, vacation,vacationcontracts) {
return $http({
method: "POST",
url: urlBase + '/' + url,
data: vacation, vacationcontracts,
async: false,
})
};
i got this error http://localhost/VacationSetupAPI/api/[object%20Object]
Any help, Thanks in advance
Try
this.save = function (vacation,vacationcontracts) {
You are sending object as 1st argument and then assigning it to the url as string, that’s wrong.
vacationsetupSrv.save(vacation, $scope.vacationcontracts);
OR
Try
vacationsetupSrv.save(“”,vacation, $scope.vacationcontracts);

How to set value string datetime (from database) to <input type="date" ng-model="endtime" name="endtime" />

As my question, this is my first time using angularjs. I try to search the solution but nothing give extactly i want.
i have list data, when update row, row value will be added to table, with datetime column, when i edit, the value can not be set to date picker (angular).
My code.
html input tag:
<input id="endtime" type="date" ng-model="endtime" />
Controller.js
$scope.editJob = function (job) {
debugger;
var getData = EmployeeService.getJobByID(job.JobID);
getData.then(function (emp) {
$scope.job = emp.data;
$scope.endtime = job.EndTime;
;
},
function () {
alert('Error in getting records');
});
}
Service.js
// Update Job
this.updateJob = function (job) {
var response = $http({
method: "post",
url: "Employee/UpdateJob",
data: JSON.stringify(job),
dataType: "json"
});
return response;
}
Index page
index
My string datetime value like : "3/1/2016"
p/s: sorry for my bad english.
If u are using Html input type date. Then assign that variable with new Date("03/25/2015");
go through this link: http://plnkr.co/edit/HcXL2TptB90skqdQznvz?p=preview
Try this
$scope.editJob = function (job) {
debugger;
var getData = EmployeeService.getJobByID(job.JobID);
getData.then(function (emp) {
$scope.job = emp.data;
$scope.endtime = $scope.job.EndTime;
;
},
function () {
alert('Error in getting records');
});
}

Restangular no BaseUrl when do PUT

i'm using Restangular and trying to PUT some data but it seems to lose the BaseUrl.
In the config function i define the BaseUrl for Restangular and others Restangular fields.
Constants.restangularBaseUrl is http://192.168.1.100/api/
RestangularProvider.setBaseUrl(Constants.restangularBaseUrl)
.setRestangularFields({
selfLink: '_links.self.href',
id: '_id',
etag: '_etag'
})
.addResponseInterceptor(function(data, operation, what, url, response, deferred){
if (operation === 'getList') {
var result = data._items;
result._meta = data._meta;
result._links = data._links;
return result;
}
return data;
});
Then i have some models like this:
(function(){
angular.module('models.ebayItems', ['services.constants', 'restangular'])
.service('EbayItems', ['Constants', 'Restangular', function (Constants, Restangular) {
Restangular.extendModel('ebayitems', function(model) {
model.toggleMonitor = function(){
var item = this;
Restangular.one('ebayitems', this._id).patch({active: this.active}, '', {'If-Match': this._etag})
.then(function(data){
item._etag = data._etag;
}, function(error){
console.log('error', error);
});
};
return model;
});
var ebayItems = Restangular.all('ebayitems');
var ebayItemsOneSearch = function(_id){
return ebayItems.customGETLIST('', {where: {searchId: _id}});
};
return {
items: ebayItems,
oneSearch: ebayItemsOneSearch
};
}])
})();
Now when i try to do a put request with an item based on that model:
item.put()
it uses the wrong url, i mean it loses the BaseUrl, so instead of putting at:
http://192.168.1.100/api/ebayitems/12345
it puts at
http://192.168.1.100/ebayitems/12345
resulting in a 404 error.
Why?
What am i doing wrong?
Any help really appreciated.
Thank you
The problem was that setting a selfLink field that was a relative url from the API backend it overrides the BaseUrl.
Removing that field from the config function it worked.
RestangularProvider.setBaseUrl(Constants.restangularBaseUrl)
.setRestangularFields({
id: '_id',
etag: '_etag'
})
.addResponseInterceptor(function(data, operation, what, url, response, deferred){
if (operation === 'getList') {
var result = data._items;
result._meta = data._meta;
result._links = data._links;
return result;
}
return data;
});

Angular and Leaflet : Looping through a promise object and copying its values

In my controller, I have a function executed on ng-init:
// Find a list of Messages
$scope.find = function() {
$scope.messages = Messages.query();
};
That's the service behind the query():
'use strict';
//Messages service used to communicate Messages REST endpoints
angular.module('messages').factory('Messages', ['$resource',
function($resource) {
return $resource('messages/:messageId', { messageId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
That's how each messag looks (aka the model):
0: Resource
$$hashKey: "00O"
__v: 0
_id: "546fb196971ba6fd20c8db62"
body: "foobar"
created: "2014-11-21T21:41:42.814Z"
location: Object
lat: 50.827409075117785
lng: 4.318828582763672
Angular has a $scope.markers object in which we can push markers that have lat and lng properties.
I need to go through the $scope.messages, get all location.lat and location.lng values and put them in $scope.markers._id.lat , $scope.markers._id.lng ..
How can we achieve this? I used angular.forEach without getting anything logged:
// Find a list of Messages
$scope.find = function() {
$scope.messages = Messages.query();
console.log($scope.messages);
angular.forEach($scope.messages, function(i, location) {
console.log($scope.messages[i]);
});
};
To access the messages from your query you need to do this:
var messages = Messages.query(function() {
console.log(messages);
});
If that correctly returns your messages to your console, your query is ok and you could then add them to your $scope.markers object:
var messages = Messages.query(function() {
angular.forEach(messages, function(obj, key) {
$scope.markers[obj._id] = {
'lat': obj.location.lat,
'lng': obj.location.lng
};
});
});

How do I do custom model data parsing in backbone.js?

While using backbone to hit an api, I've found that I need to only include some of the data in the response. The webserver is giving me back metadata in addition to data concerning my objects that I don't need.
The following solution works, but doesn't feel right. Is there a standard way of doing this?
var accountsCollection = new AccountsCollection();
accountsCollection.fetch({success : function(collection){
var results = new AccountsCollection();
collection.each(function(item){
results.add(new AccountModel({
id: item.toJSON().result[0].id,
messageText: item.toJSON().messageText,
address1: item.toJSON().result[0].address1,
address2: item.toJSON().result[0].address2
}));
});
onDataHandler(results);
}});
EDIT: This was my final solution based on the accepted answer:
parse: function(response) {
var accounts = [];
_.each(response['result'], function (account) {
accounts.push(account);
});
return accounts;
}
You could try overriding the Backbone.Collection.parse method and do some crazy underscore stuff. No idea if it fits your data..
var keysILike = ['foo', 'bar'];
AccountsCollection.extend({
parse: function(response) {
return _.compact(_.flatten(_.map(response, function (model) {
var tmp = {};
_.each(_.keys(model), function (key) {
if (_.contains(keysILike, key)) tmp[key] = model[key];
})
return tmp;
})));
}
});
With respect to #Sushanth's awesomeness you definitely want to use this solution:
var keysILike = ['foo', 'bar'];
AccountsCollection.extend({
parse: function(response) {
_.each(response, function (model) {
_.each(_.keys(model), function (key) {
if (!_.contains(keysILike, key)) delete model[key]
})
});
return response;
}
});

Resources