Add array of items into kendo ui multi select - javascript

please pardon my noobness, but I'm new to working with Telerik controls. I have seen many examples of this but they haven't been able to solve my problem. I have a Kendo UI multiselect widget which contains some items and a button which, on clicking, would fill the multiselect widget partially with some items. These items are obtained as JSON from a controller method (ASP.NET MVC). So, the button click actually fires an ajax request and on successfully firing up, it calls a javascript function to fill the multiselect widget up. As of now, the ajax gets fired successfully and the data that I want is coming back successfully, just that the multiselect is not displaying the values.
My javascript/AJAX methods:
function addItems(items) {
var values = new Array();
for (var i = 0; i < items.length; i++) {
values[i] = items[i].Item.ID;
// gets values back correctly
console.log(values[i]);
}
// print values
$('#items').data("kendoMultiSelect").value(['"' + values + '"']);
};
// success
$(document).on("click", "#add-items-button", function () {
var myUrl = $('#MyURL').val();
$.ajax({
url: myUrl, // get URL from view
method: 'GET',
dataType: 'json',
success: function (data) {
addItems(data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
My multiselect widget is a partial view so:
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelect()
.Name("items") // Name of the widget should be the same as the name of the property
.DataValueField("ID")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["items"])
.Placeholder("Add Items")
)
Am I missing something very obvious? Am I writing the data back in an incorrect format to the multiselect widget? Please help.

You need to add items to the data source of the multiselect.
$('#items').data("kendoMultiSelect").dataSource.add( { ID: 1, Name: "Name" });
Here is a live demo: http://jsbin.com/eseYidIt/1/edit

It might help to others
var multiSelect = $('#mymultiSelect').data('kendoMultiSelect');
var val = multiSelect.value().slice();
$.merge(val, "anil.singh#hotmail.com");
multiSelect.value(val);
multiSelect.refresh();
OR
$('#mymultiSelect').data("kendoMultiSelect").dataSource.add({Id:"EMP100XYZ",
EmailId: "ayz#gmail.com" });

Related

Why Dropdown list data is refilling with same values, initially I'm loading the data using page_load and next calling ajax method in asp.net c#

Initially I'm loading the ddl data using page_load and next I'm using the AJAX method and fetching the dependency data using Web Method so when I'm selecting the dependency data using `AJAX' the data is coming but the ddl is filling with previous loaded dll data I'm not sure what is the issue.
Here is my code and examples :-
Initially I'm loading the ddl data using page_load event
if (!IsPostBack)
{
firstexpdate = GetExpDates("nifty", "ce");
firststrikeprice = GetStrikePrice("nifty", firstexpdate);
lotsize = GetLotSizeVal("nifty", firstexpdate);
ltpprice = GetGreeksPrice("nifty", firstexpdate, "ce");
}
Like below I'm getting the ddl data.
And here "NIFTY" textbox is autocomplete textbox if I enter minLength: 3 this logic will execute and once enter the acc the autocomplete logic will fire and able to fetching the data from WebMethod and next I'm calling the AJAX method(because once we select the autocomplete textbox data the next ce,date,13500 ... controls data should fill autometically) for auto filling the data.
Here is how I calling the AJAX method logic
$(document).ready(function () {
//Initially I'm calling this function
autocomplete();
//Page load even I written because I used all control under the `updatepanel`
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
autocomplete();
}
});
function autocomplete() {
$("#search").autocomplete({
source: function (request, response) {
// my source logic is here and able to fetching the data successfully
//once I fetch all the symbols and next I'm calling this method
doSearch(suburbs); //Calling the Symbol Display Method{in this suburbs I'm filling the response data}
},
minLength: 3 //This is the Char length of inputTextBox
});
}
function doSearch(suburbs) {
//And here I written all my required logic and next I'm calling this method for auto fill data
//Like how I explained above query
var smbltext = $(this).text(); //Here will come `ACC` Symbol in autocomplete textbox
AutoFillUsingSymbol(smbltext); // Filling the dependency fields data
}
//This is the full logic of auto filling the controls once we select the`autocomplete`textbox data
function AutoFillUsingSymbol(symbol) {
if (symbol != '') {
var paramsmbl = { entredsmbl: symbol, selectedinstrument: $('#AutoTradeTop_Instrument option:selected').text()};
//alert(paramsmbl.entredsmbl);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AutoTrade.aspx/AutoFillData",
data: JSON.stringify(paramsmbl),
dataType: "json",
dataFilter: function (data) {
return data;
},
success: function (data) {
//Clearing before filling the data into ddl
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
var length = data.d.length;
//data.d.each(function (index, element) {
//}
$.each(data.d, function (key, value) {
//alert(value);
if (value.indexOf("-") != -1) {
//alert(value + "date found");
$("#AutoTradeTop_expdate").append($("<option></option>").val(key).html(value));
}
else {
if (!(key == length - 2 || key == length - 1)) {
//alert(value + " value found ");
$("#AutoTradeTop_strikeprice").append($("<option></option>").val(key).html(value));
}
else {
if (key == length - 2) {
//alert(value + "LotSizeVal found");
$('#autotrade_lotsizeid').html(value);
}
else if (key == length - 1) {
//alert(value + "LTP Price found");
$('#LTPliveAmount').html(value);
}
}
}
});
},
error: function ajaxError(data) {
alert(data.status + ' : ' + data.statusText);
}
});
}
}
Once this AJAX logic hit AutoFillUsingSymbol(symbol) It will go to WebMehod logic and able to fetching the required data and filling into ddl list.
before filling into ddl data I'm clearing(emptying the dropdown list data) the ddl data and refilling
$('#AutoTradeTop_expdate').empty();
$('#AutoTradeTop_strikeprice').empty();
$('#autotrade_lotsizeid').html('');
$('#LTPliveAmount').html('');
Here is the example image of auto filling data once we select acc symbol and date is loading what I selected symbol acc
But if I select any one date the dropdown list data is clearing and filling the previous symbol data `nifty' see the above first image for reference.
example image
Note :- I know if we fill or change the dropdownlist client side code, then the list of values does not persist but initially I filled the ddl data in the page_load event and next I wrote the AJAX method but why the values are not loading properly.
Suggest me what is the issue and where I did the mistake
I'm beginner in the client side code development .

Updating a div based on a select event from KendoUI Widget

I have a KendoUI search bar that has a drop down of autocompleted items based on what I type. When I type into I get a drop down menu. When I click on an item in the drop downlist, I want two things to happen. One which works, and that is loading a partial view. But, the other thing deals with updating a div element that is also in that partial view.
The partial view
#{
ViewBag.Title = "Client";
}
<div id="update">#ViewBag.name</div>
<p id="ahhh"></p>
External Javascript function
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
alert("IT WORKED");
},
error: function (result) {
alert("FAILED");
}
})
}
In the HomeController there is a method called someStuf. I am sending that item that is clicked on the event into the someStuf method.
Now here are the two controller methods that I'm working with.
Secretary s = new Secretary();
public ActionResult Client()
{
ViewBag.name = s.Client;
return PartialView();
}
[HttpPost]
public JsonResult someStuf(String n)
{
s.Client = n;
return Json(n, JsonRequestBehavior.AllowGet);
}
So then I update a class with that value that was passed from javascript. I then add that new value to the viewbag for the partial view Client.
Sorry for the misleading variables. Client is a type of model. Then I always have a partial view that is called client.
When I try this. The ViewBag is not showing the result that I would like. I can get the client side to send to the server. But I can't get the server to send to the client.... I bet it's something simple. But I'm trying to understand this step so I can use the same method to update id and class elements.
<p class="CompanySearchBar">
#(Html.Kendo().AutoComplete()
.Name("companyComplete") //The name of the AutoComplete is mandatory. It specifies the "id" attribute of the widget.
.DataTextField("company") //Specify which property of the Product to be used by the AutoComplete.
.BindTo(Model)
.Filter("contains")
.Placeholder("Company name")
.Events(e => { e.Select("onSelect"); })
)
</p>
The above code allows for a search bar with autocomplete. While typing for an item a drop down list shows up with results having the same substring. When clicking one of the results the onSelect method is activated.
you can give like this and on change event just assign a value using jquery like
function onSelect(e) {
$("#navResult").load('/Home/Client');
var value = e.item.text();
alert(value);
$.ajax({
type: "POST",
url: "Home/someStuf",
dataType: "json",
data: {n: value },
success: function (result) {
$('#ahhh').text(result.NAME); //the object which you returns from the controller
},
error: function (result) {
alert("FAILED");
}
})
}
<label id=ahhh></label>

jQuery - Add row to datatable without reloading/refreshing

I'm trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page.
Here is my code
//show data page onload
$(document).ready(function() {
catTable = $('#cat_table').DataTable( {
columns: [
{ title: "Name" },
{ title: "Level" },
{ title: "Create Date" },
{ title: "Status" }
]
});
get_cat_list();
});
//save new entry and refresh data list
$.ajax({
url: 'category_save.php',
type: 'POST',
data:{name: name,level: level},
success: function (data) {
get_cat_list();
},
error: function (data) {
alert(data);
}
});
//function to retrieve data from database
function get_cat_list() {
catTable.clear();
$.ajax({
url: 'get_category_list.php',
dataType: 'JSON',
success: function (data) {
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
] );
});
}
});
}
The solution is here - for DataTable server side data source enabled
.draw() will cause your entire datatable to reload, say you set it to show 100 rows, after called .row().add().draw() > datatable will reload the 100 rows again from the server
I wasted an hour trying to find any solution for this very old question, even on DataTable official support there is no good solution suggested ...
My solution is
1- call .row().add()
2- do not call .draw()
3- your row must have an Id identifier to use it as a selector (check the rowId setting of the datatable)
4- after calling .row().add(), the datatable will have the row added to it's local data
5- we need to get this row from datatable object and transform it to HTML using the builtin method .node()
6- we gonna prepend the result HTML to the table :)
All that can be done in two lines of code
var rowData = someRowCreatedByAnAjaxRequest;
myDataTableObject.row.add(rowData);
$("#myTable-dt tbody").prepend(myDataTableObject.row(`tr#${rowData.Id}`).node().outerHTML)
Thanks ☺
From the documentation,
This method will add the data to the table internally, but does not
visually update the tables display to account for this new data.
In order to have the table's display updated, use the draw() method, which can be called simply as a chained method of the row.add() method's returned object.
So you success method would look something like this,
$.each(data, function() {
catTable.row.add([
this.name,
this.level,
this.create_date,
this.status
]).draw();
});

Send Chosen Selected Values Array to Controller - MVC

So, I have a view with a chosen search box, a button "Add" (btn-default) and a button "Edit" (breadcrumb) . When I click the Add button, the ajax sent me a table with the values (in this case, funcionaries) selected in the chosen text box.
I want that, when I click on the Edit button, send the chosen values (can be one, or hundreds of values) to another controller to return another view.
Don't want to use ajax because I want to use a new view on totally.
On the controller side, when I send the data with javascript, I always get null. Why?
View
<script>
$(document).ready(function () {
$(".btn-default").on("click", function (event, params) {
$.ajax({
url: '#Url.Action("EditarPonderacoesEspecial", "Sorteios")',
type: 'POST',
dataType: 'html',
cache: false,
traditional: true,
data: { bdoIds: $(".chosen-select").val() },
success: function (responseText, textStatus, XMLHttpRequest) {
$("#MyDiv").empty();
$("#MyDiv").html(responseText);
},
error: function () { }
})
});
$(".breadcrumb").on("click",function (event, params) {
bdoIds = $(".chosen-select").val();
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", bdoIds);
});
});
Controller
public ActionResult EditarPonderacoesEspecialSecond(string[] bdoIds)
{
//do whatever I want with the bdoIds
return View();
}
I had tried many different ways, but the controller always receive the parameter as null. What I am doing wrong? Thanks!
Your controller action is expecting an array of strings.
Assuming .chosen-select is a select list as that part is missing from the question.
First read the selected values into an object as follows:
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
Then send them as follows:
$(".breadcrumb").on("click",function (event, params) {
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", { bdoIds: selectedValues });
});
Declare Global array like
var SelectedArray = new Array();
When you select multiple selectlist item each time push value in SelectedArray
$('#ChosenId').chosen().change(function () {
SelectedArray = $('#ChosenId').chosen().val();
});
Then your ajax data is like
data: { bdoIds: SelectedArray },

Telerik MVC Grid - Pass Value to New Controller Action

Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.

Categories