Options binding with Knockout - asp.net-mvc

Sure this must be something stupid I'm doing but I'm having a real issue populating a select element and setting the selected value using Knockout to consistently work. I have a ASP.NET view which has a number of select options and I need to set the selected values with data from the server.
Sometimes these bind correctly but more often than not the selectedValue is not selected - is it the order I'm doing things in?
When using ko.mapping to setting observable properties I can't get this to work at all so have been setting individual observables values but even this doesn't work all the time.
<select data-bind="options: possibleValues, optionsText: 'Value', optionsValue: 'Id',value: selectedValue, optionsCaption: 'Select Value...'">
function ViewModel() {
var self = this;
self.selectedValue = ko.observable();
self.possibleValues = ko.observableArray();
function GetValues() {
$.ajax({
url:"http:/abc.com/api/GetValues",
dataType: "json",
type: "GET",
data: {},
success: function(data) {
$.each(data.values, function(i,option){
self.possibleValues.push(option);
});
}
}
function GetInitialValue() {
$.ajax({
url:"http:/abc.com/api/GetValue",
dataType: "json",
type: "GET",
data: {},
success: function(data) {
*using ko.mapping doesn't work at all?*
self.selectedValue1(data1.Id)
self.selectedValue2(data2.Id)
self.selectedValue3(data3.Id)
}
});
}
}
ko.applyBindings(new ViewModel());

Related

Change kendo grid data with ajax call

I populate a kendo grid from my model which works fine. I want to be able to change the datasource of the grid via an ajax call which is different from the initial load and subsequent trips to filter. My ajax call is returning the model data in json, but the data in the grid does not change. How do I change the datasource and rebind the grid?
Initial population and filtering
#(Html.Kendo().Grid(Model.Catalogs)
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax().ServerOperation(false)
.Read(read => read.Action("Index", "Catalog"))
)
Ajax call where I want to repopulate the grid with json. result.Catalogs does contain the proper data:
$("#btnPartNumberSearch").on('click', function () {
$.ajax({
type: "POST",
url: "Catalog/PartNumberSearch",
data: JSON.stringify({
PartNumber: $("#Partnumber").val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.isCatalogSearch) {
$('#inventoryItems').hide();
$('#catalogItems').show();
$("#grid").data(result.Catalogs);
}
else {
$('#inventoryItems').show();
$('#catalogItems').hide();
$("#grid").data(result.Inventory);
}
},
error: function(){
alert("error");
}
});
});
Your syntax is off:
var grid = $("#grid").data("kendoGrid");
grid.dataSource.data(result.Catalogs);
or you could create a new datasource (might impact column settings):
var dataSource = new kendo.data.DataSource(result.Catalogs);
var grid = $("#grid").data("kendoGrid");
grid.setDataSource(dataSource);
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource

Passing "data-" to controller

I have the following code...
HTML:
<button type="button" class="btn btn-primary" id="filterData"
data-filterString="#Model.LastName">Filter</button>
TypeScript:
$("button[id='filterData']").click(() => {
var dataList = [];
var filter = $(this).data("filterString");
$("input[class='personRecord']").each(function() {
dataList.push($(this).val());
});
var parameters = JSON.stringify({ "filterString": filter, "dataList":paymentList });
$.ajax({
url: "/Employee/FilterName",
data: parameters,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("Success");
}
});
});
Controller:
[HttpPost]
public void SendAll(string filterString, List<string> dataList) {
...
}
However, the variable filter keeps returning "undefined". How do you pass custom data items, data-filterString in this case?
In your jQuery, you can only use lower case values for the data method, even if your attributes are upper/mixed case. So you should write:
var filter = $(this).data("filterstring");
If you do use mixed case in your key, jQuery converts that to a dashed variable, so when you search for filterString, your attribute should be called data-filter-string.
$(function() {
console.log($('#test').data('filterstring'));
console.log($('#test').data('filterString'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test" data-filterString="value1" data-filter-string="value2"></div>

How to use ajax in mvc?

I am a very beginner to mvc and ajax both.
I have tried many examples on net but I don't understand how ajax is used practically?
I have a controller named members which has GetAllMembers Method.
GetAllMembers returns a List<Members>
Now I want to use JQuery and ajax something like :
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function () {
},
error: function () {
alert("Failed to get the members");
}
});
});
Is my URL right?
Upon success I want to display that List in a ListBox.
How can I get it? Can anyone give me a start?
$.ajax({
type: "POST",
url: "Members/GetAllMembers", //Your required php page
data: "id="+ data, //pass your required data here
success: function(response){ //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page.
},
error: function () {
alert("Failed to get the members");
}
});
Hope this will help you.. :)
$(document).click(function () {
$.ajax({
url: "Members/GetAllMembers",
success: function (result) {
// do your code here
},
error: function () {
alert("Failed to get the members");
}
});
});
So your request give response in "result" variable. So you have to easily manage result variable value in foreach loop and set value in ListBox HTML.
Follow this example:
suppose you have this html:
<p>List Box - Single Select<br>
<select id="listBox" name="listbox">
</select>
</p>
So we have this js:
var template = '<option value="$value">$name</option>';
var getAllMembers = function() {
$.ajax({
url: 'Members/GetAllMembers',
dataType: 'json', //Assuming Members/GetAllMembers returns a json
success: function(response) {
$.each(response, function(index){
var option = template.replace(/\$value/g, this.value)
.replace(/\$name/g, this.name);
$('#listBox').append(option);
});
}
});
};
EDIT: Now you only need to call getAllMembers(); function.
Hope this help.
Pablo.

jquery Select2 Ajax - How set value (initSelection)

How set in the drop-down list item selected by the user?
Scenario:
1. User not enter all required values in form
2. Click sent.
3. Page is refresh and value in dropdown list is not selected. How select the value?
I have working script which retrieve data for the list.
$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
url: "index.php?modul=getusers",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return { results: data };
}
},
allowClear: true,
formatSelection: function(data) {
return data.text;
}
});
Standard data in ajax call:
{"text":"sample text", "id":"1"}
Input:
<input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid">
I tried to add the following code, but it doesn't work
initSelection: function(element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.php?modul=getusersfriend&q="+id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
Make sure that you have a properly formatted JSON Object being returned in your call back in initSelection. The discussion for that has been addressed here already.
But so far looks good. You may want to bind the change event of the select or the submit event of the form to serialize its value before the form is submitted.
You can store its value on your server (yucky) or just serialize the form object and get the value to pass to initSelection when the select2 is loaded.
Which is what would happen here:
var id=$(element).val();
Here is a simple example of serializing your form.
PS: Don't really see what bootstrap has to do with anything.

Set the value and display property for jquery's autocomplete source

I've got a remote source which does not return id and value or label. How can I use it as a source for jquery's autocomplete plugin?
You should pass source a function that makes the AJAX request manually, and then performs some post-processing on the returned data:
source: function(request, response) {
$.ajax({
url: url,
data: request,
dataType: "json",
success: function(data) {
var processedData = $.map(data, function(item) {
return {
value: item._your_property, // Property you want to use for "value"
label: item._another_property // Property you want to use for "label"
}
});
response(processedData);
},
error: function() {
response([]);
}
});
}
Basically, use $.map to turn the array you get back into an array of objects that the autocomplete widget supports.
For a working example, check out the JSONP example on jQueryUI's demo page.

Resources