I am trying to populate data into Select2 dropdown using JSON which is returned by a controller class.But it is not working.There is no error.Here is the code
client Side
$("#products").select2({
minimumInputLength: 2,
ajax: {
url: "Search",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
"q": JSON.stringify(term),
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
Controller Action
[HttpPost]
public JsonResult Search(string q)
{
//testing data
return Json(new products() {id = "2", text = "biotouch"});
}
Product class
public class products()
{
public string id{get;set;}
public string text{get;set;}
}
It worked when I changed
results: function (data) {
to
ProcessResults: function (data) {
$("#products").select2({
minimumInputLength: 2,
ajax: {
url: "YourControllerName/Search",
dataType: 'json',
type: "POST",
quietMillis: 50,
data: function (term) {
return {
"q": JSON.stringify(term),
};
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
});
I have added controller name in URL you forgot to add controller name in url.
Related
I need to setup my datasource to use localForage to manage my offline data storage.
The problem I'm having is that localForage is asynchronous by nature, only allowing us to use a callback or a promise to retrieve data.
This is how my code is set-up:
(function () {
'use strict';
var serviceId = 'employeeDataSource';
angular.module('app').factory(serviceId, function () {
var crudServiceBaseUrl = 'Data/Employees';
var dataSource = new kendo.data.DataSource({
type: "odata",
offlineStorage: {
getItem: function () {
localforage.getItem('employees-key').then(function (value) {
console.log(value);
return JSON.parse(value);
});
},
setItem: function (item) {
if (item.length > 0) {
localforage.setItem("employees-key", JSON.stringify(item));
}
}
},
transport: {
read: {
url: crudServiceBaseUrl + "/",
dataType: "json"
},
update: {
url: function (data) {
return crudServiceBaseUrl + "(guid'" + data.EmployeeId + "')";
}
},
create: {
url: crudServiceBaseUrl
},
destroy: {
url: function (data) {
return crudServiceBaseUrl + "(guid'" + data.EmployeeId + "')";
}
}
},
batch: false,
pageSize: 5,
serverPaging: true,
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data['odata.count'];
},
model: {
id: "EmployeeId",
fields: {
EmployeeId: { editable: false, nullable: true },
Name: { validation: { required: true } },
Email: { validation: { required: true } },
IsManager: { type: "boolean" },
MaxHolidaysPerYear: { editable: false, type: "number", validation: { min: 0, required: true } },
HolidaysLeftThisYear: { type: "number", validation: { min: 0, required: true } }
}
}
},
error: function (e) {
if (e.xhr.responseText !== undefined) {
console.log(e.xhr.responseText);
}
}
});
dataSource.online(navigator.onLine);
$(window).on("offline", function () {
dataSource.online(false);
});
$(window).on("online", function () {
dataSource.online(true);
});
return dataSource;
});
})();
When off-line, the getItem gets called, then the setItem gets call as well with an empty array, hence the:
if (item.length > 0) {
localforage.setItem("employees-key", JSON.stringify(item));
}
When the promise finally returns the off-line data (with the correct values I expected), the Grid displays no results.
This behaviour is presumably because of the promise ?
I tried the same thing with sessionStorage and its worked perfectly... i.e.:
getItem: function () {
return JSON.parse(sessionStorage.getItem("employees-key"));
},
setItem: function (item) {
sessionStorage.setItem("employees-key", JSON.stringify(item));
}
What can I do to get around this?
Just got a heads-up from Telerik
There is an issue logged in their GitHub repo about the same problem.
You can keep track on the progress here:
https://github.com/telerik/kendo-ui-core/issues/326
I have a working sample with hardcoded data. I am trying to convert it to ajax call using bootstrap-typehead. I am not sure what I am doing wrong, but consol is shwoing error. Could some one help ? Thanks!
//Error
LOG: [object Object],[object Object],[object Object],[object Object]
SCRIPT438: Object doesn't support property or method 'toLowerCase'
JSFIDDLE
$('#selectAgent').typeahead({
source: function (query, process) {
return $.post('/eBus/EbusinessAgentServlet', { query: query }, function (data) {
console.log(data)
return process(data);
});
}
,
minLength: 2,
highlighter: formatRecord,
updater: function (item) {
$('#selectAgent').attr('data-agent-id', item.split('#')[1]);
return formatRecord(item);
}
});
It is working now.
var nameIdMap = {};
$('#selectAgent').typeahead({
source: function (query, process) {
return $.ajax({
dataType: "json",
url: '/eBus/EbusinessAgentServlet',
data: 'q=' + query,
type: 'POST',
success: function (json) {
console.log(json)
process(getOptionsFromJson(json));
}
});
},
minLength: 2,
updater: function (item) {
console.log('selected id'+nameIdMap[item]);
return item;
}
});
});
function getOptionsFromJson(json) {
$.each(json, function (i, v) {
nameIdMap[v.fname] = v.agentID;
});
return $.map(json, function (n, i) {
return n.fname;
});
}
function getAjaxRequestData(query) {
return {
json: getJsonData(query),
delay: 1
};
// in the question this would be:
// return 'q='+query;
}
I think that because you're using ajax but javascript is has asyn (default) so you can try to using ajax this way to set async: false . Hpe this help.
$('#selectAgent').typeahead({
source: function (query, process) {
return $.ajax({
url: "/eBus/EbusinessAgentServlet",
data: { query: query },
type: "POST",
async: false,
success: function (data) {
console.log(data)
return process(data);
}
});
},
minLength: 2,
highlighter: formatRecord,
updater: function (item) {
$('#selectAgent').attr('data-agent-id', item.split('#')[1]);
return formatRecord(item);
}
});
I have my AJAX call
$.ajax({
type: 'post',
url: "/Store/LoadStoreIndex",
data: , //Entire Model Here!!
dataType: "text",
success: function (result) {
$('#Postback').html(result);
}
});
I need to send my entire model back to the controller, but after much searching can't find anything ... Can somebody show me what I need to be doing?
Controller Get Action
public ActionResult Index(YourModel model)
{
YourModel model = new YourModel();
return View(model);
}
View
#model YourModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.TextBoxFor(x => x.EmailAddress)
#Html.TextBoxFor(x => x.Name)
...
}
Script
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
// you can post your model with this line
data: $(this).serialize(),
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
},
error: function () {
}
});
}
return false;
});
});
Controller Post Action
[HttpPost]
public ActionResult Index(YourModel model)
{
return View();
}
From a page Index.cshtml, i have a very simple ajax call
controller1 and controller2 have the same action:
public ActionResult abc(string name)
{
return new JsonResult()
{
Data = new
{
success = true,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
}
};
}
$(document).ready(function ($) {
$.ajax({
url: '#Url.Action("abc", "controller1")',
type: 'POST',
data: { name: 'John' },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("ok");
}
else {
alert(result.error);
}
}
});
});
not work
however using exactly the same syntax, just change the controller, it works !!!.
abc action is the same.
$.ajax({
url: '#Url.Action("abc","controller2")',
type: 'POST',
data: { name: 'John' },
dataType: 'json',
success: function (result) {
if (result.success) {
alert("ok");
}
else {
alert(result.error);
}
}
});
it drives me crazy, don't know what happen. On a new project, i tried the same code, it works perfectly, but not on my current work.
I want to access view data In Java script in following code
public virtual ActionResult Edit(MyModel _MyModel)
{
//some Code
if (true..)
{
ViewData["Messages"] = "Data Updated Sucessfully";
}
else
{
ViewData["Messages"] = "you cannot Updated data";
}
return View();
}
In javascript
function SaveData() {
$("#btnSave").click(function () {
// $('#divLoadImage').show();
// $('#divOverlay').show();
// debugger;
$.ajax({
type: "POST",
url: "Admin/Edit/",
data: "",
complete: function () {
alert(ViewData["Messages"]);
}
});
});
}
it give me no value in alert..
You need to encode it using for example the JavaScriptSerializer class:
function SaveData() {
$("#btnSave").click(function () {
$.ajax({
type: "POST",
url: "Admin/Edit/",
data: "",
complete: function () {
alert(#Html.Raw(new JavaScriptSerializer().Serialize(ViewData["Messages"])));
}
});
});
}
or use simple quotes but be careful as this might break if the message contains quote so I wouldn't recommend you this:
alert('#ViewData["Messages"]');