I am using x-editable to populate select list in popup. Now I want to send my key to server, my code is something like that
<a href="#" id="status" data-type="select" data-pk="1" data-url="${g.createLink(controller: 'someController', action: 'someAction')}" data-title="Select CV" class="btn btn-primary">
<image src="${resource(dir: 'images/template', file: 'logo11.png')}"/> ${session.someList?.size()} CV(s) Created
</a>
<script>
$(function () {
$('#status').editable({
value: 1,
source: [
<g:each in="${session.someList}" var="xyz" status="idx">
{value: ${xyz?.id}, text: "${xyz.title}", srsSelected: ${xyz.id}, updateXyz: "updateXyz"},
</g:each>
]
});
});
</script>
I want to send my srsSelected key to server, I did google but not getting the point...
Edit:
Now I am able to send my key to server(after long research) using
params: function (params) { //params already contain `name`, `value` and `pk`
var data = {};
data['cvSelected'] = params.pk;
return data;
}
therefore my updated code is:
<a href="#" id="status" data-type="select" data-pk="1" data-url="${g.createLink(controller: 'someController', action: 'someAction')}" data-title="Select CV" class="btn btn-primary">
<image src="${resource(dir: 'images/template', file: 'logo11.png')}"/>
${session.someList?.size()} CV(s) Created
</a>
<script>
$(function () {
$('#status').editable({
value: 1,
source: [
<g:each in="${session.someList}" var="xyz" status="idx">
{value: ${xyz?.id}, text: "${xyz.title}", srsSelected: ${xyz.id}, updateXyz: "updateXyz"},
</g:each>
],
params: function (params) { //params already contain `name`, `value` and `pk`
var data = {};
data['srsSelected'] = params.pk;
return data;
}
});
});
</script>
I am able to send value of pk in srsSelected key but this time I need to set value of srsSelected dynamically.
And Now I found the method to set the value of srsSelected dynamically as
params: function (params) {
params.srsSelected = params.pk
return params;
}
and setting the value of data-pk attribute in anchor tag dynamic, we can get srsSelected at controller action.
Related
I am using Kendo ListView with remote datasource. I would like to add links to the data that is displayed but I am struggling.
Here is my function:
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: URL + "/Read",
dataType: "json"
}
},
schema: {
data: function (response) {
return response.Data["dsStudent"]["ttStudent"];
},
},
});
$("#listView").kendoListView({
dataSource: dataSource,
selectable: "multiple",
dataBound: onDataBound,
change: onChange,
template: kendo.template($("#template").html())
});
function onDataBound() {
//console.log("ListView data bound");
}
function onChange() {
var data = dataSource.view(),
selected = $.map(this.select(), function (item) {
return data[$(item).index()].fileID;
});
console.log("Selected: " + selected.length + " item(s), [" + selected.join(", ") + "]");
}
});
Here is my template
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<ul class="list-group">
<li class="list-group-item">#:Name#</li>
</ul>
</div>
</script>
The data is displayed as expected. My JSON contains a value that I would like to append to a url, this would then be used to create the href link. This is where I am struggling.
I have been able to console.log the value I need form my JSON but I am lost trying to figure out how to create the href.
Here is a snippet of my JSON:
{"Data": {"dsStudent": {"ttStudent": [{"studentNum": 366,"studentVersion": 2,"createDate": "2018-02-11","fileID":"18525478387e8","description":"StudentNames.pdf","displayCreateTime": "15:31"}]}}}
Using the onChange function, I am able to console.log the required field from the JSON.
I am trying to output the results like this, the fileID would change for each record in the JSON file.
<ul>
<li>
Download Student Record
</li>
</ul>
I hope I have been able to explain where I am struggling.
Just do like in your first template, print the value:
Download Student Record
^ here is where you print the fileId inside the link address
I am trying to create a multiple choice list using Select2, Razor and the MVC framework. My problem is that the object in the controller that receives the array input is always null. The front-end looks as follows:
<form class="form-horizontal" method="post" action="#Url.Action(MVC.Configurazione.Contatori.Edit())">
<div class="form-group">
<div class="col-lg-8">
<select class="form-control attributoSelect2" name="attributiSelezionati" value="#Model.AttributiSelezionati">
<option value="#Model.AttributiSelezionati" selected>#Model.AttributoDescrizione</option>
</select>
</div>
</div>
</form>
The action method "Edit", is the controller method that receives the array of chosen items from the drop-down list.
The Javascript is the following:
$('.attributoSelect2').select2({
placeholder: "Search attribute",
multiple: true,
allowClear: true,
minimumInputLength: 0,
ajax: {
dataType: 'json',
delay: 150,
url: "#Url.Action(MVC.Configurazione.Attributi.SearchAttrubutes())",
data: function (params) {
return {
search: params.term
};
},
processResults: function (data) {
return {
results: data.map(function (item) {
return {
id: item.Id,
text: item.Description
};
})
};
}
}
});
And finally the C# controller has an object that is expected to retrieve the data from the view and is defined:
public string[] AttributiSelezionati { get; set; }
and the HttpPost method that receives the data is:
[HttpPost]
public virtual ActionResult Edit(EditViewModel model) { }
Could someone give me some insight into what I am doing wrong and the areas that I should change in order to find the problem?
you class name error not attributoSelect2 is attributesSelect2 , I also make this mistake often. haha
<select class="form-control attributoSelect2" name="attributiSelezionati" value="#Model.AttributiSelezionati">
<option value="#Model.AttributiSelezionati" selected>#Model.AttributoDescrizione</option>
</select>
There are multiple reason for not being receiving data on server. First of all you need to change your select code as follow
#Html.DropDownList("attributiSelezionati", Model.AttributiSelezionati, new { #class = "form-control attributo select2" })
now go to console in browser and get the data of element to confirm that your code properly works in HTML & JS
After that you need to add attribute at your controller's action method as
[OverrideAuthorization]
[HttpPost]
You can try the following approach that has been used in some of our projects without any problem:
View:
#Html.DropDownListFor(m => m.StudentId, Enumerable.Empty<SelectListItem>(), "Select")
$(document).ready(function () {
var student = $("#StudentId");
//for Select2 Options: https://select2.github.io/options.html
student.select2({
language: "tr",//don't forget to add language script (select2/js/i18n/tr.js)
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: false,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
url: '/Grade/StudentLookup',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.Name + " " + item.Surname
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }
});
//You can simply listen to the select2:select event to get the selected item
student.on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}
//Event example for close event
student.on('select2:close', onClose)
function onClose(evt) {
console.log('Closed…');
}
});
Controller:
public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name,
Surname = m.Surname
})
//if "query" is null, get all records
.Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query))
.OrderBy(m => m.Name);
return Json(students, JsonRequestBehavior.AllowGet);
}
Hope this helps...
Update:
Dropdown option groups:
<select>
<optgroup label="Group Name">
<option>Nested option</option>
</optgroup>
</select>
For more information have a look at https://select2.org/options.
I'm trying to turn the results of a route from my API into a searchable list the whole process of obtaining data via AJAX is completed, I can print data on my front end but only 1 result from my list in JSON is available to the client, how can I expand this list using statement?
Jquery
$('#sendSearchAddress').click(function() {
$.ajax({
type: "GET",
dataType: "JSON",
url: "https://****/api/itapetininga-street-last-three-searcheds?access_token=7Z***",
success: function (finalData) {
// Running test
console.log(finalData);
if (finalData) {
// var dd = JSON.parse(result);
// alert(finalData[0].addressStreet)
// name: finalData[0].addressStreet
// Print Results
var options = {
valueNames: ['name', 'born']
};
// Example One
var values = [{
name: finalData[0].addressStreet
}];
var userList = new List('users', options, values);
// Example Two
// userList.add(values);
// Print Varible Contain Data From Street
console.log(values);
}
}
});
});
Html
<div id="users">
<input class="search" placeholder="Search" />
<button class="sort" data-sort="name">
Sort by name
</button>
<button id="sendSearchAddress">
Atualizar
</button>
<ul class="list">
<li>
<h3 class="name">Jonny Stromberg</h3>
<p class="born">1986</p>
</li>
<li>
<h3 class="name">Jonas Arnklint</h3>
<p class="born">1985</p>
</li>
</ul>
</div>
My JSON Result
I'm not sure I fully understand what you're trying to do but as best as I can tell it looks like you need to change
var values = [{
name: finalData[0].addressStreet
}];
to
var values = finalData.map(function(finalDatum) {
return {
name: finalDatum.addressStreet
};
});
Hi I'm using angularJs in my client side. I have a view where a user can add and remove item like this:
app.controller('demoController', function($scope) {
// initial items
$scope.items = [
'item one',
'item two',
'item three'
];
// add an item
$scope.add = function() {
$scope.items.push($scope.input);
};
// remove an item
$scope.remove = function(index) {
$scope.items.splice(index, 1);
};`enter code here`
});
When the user finish, I want he clicks on a button. And after I will send all the items added and removed to a server to update database. I can't do this on each click because I need all the information to fill an email in my server part. I know how to remove and add item but I don't how to found removed items and add items and send them to the server. Please any one know how I can do this?
Thanks a lot.
You can do it with only using 1 array. You just have to create a new property and set it to true - if removed -, or false otherwise.
Then in your back-end you can get all the removed items accessing this property.
See the example below:
(function() {
'use strict';
angular
.module('app', [])
.controller('demoController', demoController);
demoController.$inject = ['$scope'];
function demoController($scope) {
// initial items
$scope.items = [
{
"name":"item one",
"removed":false
},
{
"name":"item two",
"removed":false
},
{
"name":"item three",
"removed":false
}
];
// add an item
$scope.add = function() {
$scope.items.push({
"name": $scope.input,
"removed": false
});
};
// remove an item
$scope.remove = function(index) {
$scope.items[index].removed = !$scope.items[index].removed;
};
}
})();
<!DOCTYPE HTML>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body ng-controller="demoController">
<table class="table table-hover">
<thead>
<tr>
<td>Name</td>
<td>Removed?</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items track by $index">
<td ng-bind="item.name"></td>
<td ng-bind="item.removed"></td>
<td>
<button type="button" class="btn btn-danger btn-sm" ng-click="remove($index)">Remove item</button>
</td>
</tr>
</tbody>
</table>
<hr>
<input type="text" class="form-control" ng-model="input" placeholder="Type to add">
<button type="button" class="form-control btn btn-primary btn-sm" ng-click="add()">Add item</button>
</body>
</html>
Note: If you don't want to show the removed items, you can simply check in your tr:
<tr ng-repeat="item in items track by $index" ng-if="!item.removed">
Now if you want to send both added and removed you have to actually store the removed ones somewhere either in the object itself with a flag like #developer033 suggested or either in an other object.
For me it is better to store all added and removed elements in one object. Now you do not need to click a button and send the change on every add or remove. When you are done with adding and removing you can just simply send the whole object with AJAX request to the server where you can do your logic:
function demoController($scope, $http, $q) {
$scope.submitItems = function(){
sendItems($scope.items).then(function () {
alert("Successfully deleted PT");
}, function (error) {
alert(error);
});
};
// ....
var sendItems = function (items) {
var request = $http({
url: _SERVER + 'edit/sendItems', // for example
method: 'POST',
data : items
params: {
}
});
return request.then(function (data) {
return $q.when(data);
}, function (error) {
return $q.reject(error);
});
}
// ....
}
It is a good practise to have a service from where you call the server and where this method sendItems should be. But we try to keep at as simple as possible.
Now in your rest controller in Spring you have to specify #RequestBody param:
#RequestMapping(value = "/sendItems", method = RequestMethod.POST)
public String editProductParameters(#RequestBody ArrayList<Item> items) {
//your logic goes here
return "Success"
}
Where the Item.class should consist the fields: String name and boolean remove also should have a deffault constructor(deffault constructur is specified if there are none implementations of constructurs in the class or if there is a constructor with no arguments) also create getters and setter about the two fields. Thouse are the requirements that are needed to pass the whole array of objects($scope.items) from the client to the server with default mapping.
Good luck
I want to filter in the list if the text box value is changed if the
JSON Returned in Ajax call is as I am using two different model.
Filteration should show hide or just filter the data I am providing you the JSON data what I am getting from the ajax call. Thanks
Data = [{"code":"Grand Financial","cls":"Branch","Chk":true},{"code":"Joan Group","cls":"Branch","Chk":true}]
var searchModel, advisorGroupModel;
$(document).ready(function () {
$.ajax({
type: "GET",
url: '/ASPNET/Reports/GetAdvisorGroups',
dataType: "json",
success: function (data) {
advisorGroupModel = {
advisorGroup: ko.observableArray(data)
};
ko.applyBindings(advisorGroupModel, document.getElementById("advisorGroupModel"));
}
})
var searchModel = {
searchQuery: ko.observable('')
};
searchModel.searchHandle= ko.dependentObservable(function () {
var code = this.searchQuery().toLowerCase();
return ko.utils.arrayFilter(advisorGroupModel, function (beer) {
debugger;
return beer.code.toLowerCase().indexOf(code) >= 0;
});
console.log(search);
}, searchModel)
ko.applyBindings(searchModel, document.getElementById("searchModel"));
});
<div id="searchModel">
<input data-bind="value: searchQuery, valueUpdate: 'keyup'" />
<h6 data-bind="text: searchQuery"></h6>
</div>
<div class="CheckBoxListGroup" id="advisorGroupModel">
<ul data-bind="template: { name: 'advisorGroupTemplate', foreach: advisorGroup, as: 'singleAdvisorGroup' }"></ul>
<script type="text/html" id="advisorGroupTemplate">
<li>
<input type="checkbox" data-bind="attr: { value: code, id: code, checked: Chk }" name="GroupsSel">
<label data-bind="attr: { for: code }, text: '' + code + ' (' + cls + ')' "></label>
</li>
</script>
</div>
don't bind your display to the entire list, bind your display to a computed function that returns the filtered list or returns all items when there are no filters.
then on your keyup call your filterlist function that filters the list removing the ones that do not match your filter