Appropriate js kendo template for website - javascript

I use only kendo template in my website and use this js:
kendo.cdn.telerik.com/2015.2.805/js/kendo.all.min.js
but this file very very large size (2.102 KB). I want Appropriate kendo js file for this sulotion but I dont know:
my codes is:
<script>
function FillSpecificationAttr(attrId) {
var template = kendo.template($("#template").html());
var ID = attrId;
var dataSource = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: "../AjaxFunctionPages.asmx/ProductSpecAttrList",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
ID: ID
}
},
destroy: {
url: "../../AjaxFunctionsAdminPages.asmx/TierPriceDelete",
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
ID: ID
}
},
parameterMap: function (data, operation) {
if (operation != "read") {
// web service method parameters need to be send as JSON. The Create, Update and Destroy methods have a "products" parameter.
return JSON.stringify({ ID: data.Id })
}
else if (operation == "destroy") {
}
else {
// web services need default values for every parameter
data = $.extend({ sort: null, filter: null }, data);
return JSON.stringify(data);
}
}
},
schema: {
data: "d.Data"
},
requestStart: function () {
kendo.ui.progress($("#tblConfigProduct"), true);
},
requestEnd: function () {
kendo.ui.progress($("#tblConfigProduct"), false);
},
change: function () {
$("#tblConfigProduct").html(kendo.render(template, this.view()));
}
});
dataSource.read();
};
</script>

I think the template is defined in kendo.core.min.js file which in version 2017.2.504 is only 54KB of size. You will still need jQuery library as a required dependency added in your document.
Demo

Related

How to pass local storage item to MVC controller

I am trying to pass an array of strings from my local storage (key value) to MVC controller. Here's my code:
In cshtml View file:
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.Result);
}
}});
}
</script>
<button onClick="getFavouriteBooks()">Display Favourites</button>
My controller:
public async Task < ViewResult > Favourites(string ids) {
// code that fetches book data from API
if (data != null)
{
var bookList = JsonConvert.DeserializeObject < Book[] > (data);
foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
}
return View("Index");
}
The controller action gets called successfully on the button click but the ids parameter is always null even though it isn't when in the console. Where am I going wrong?
from what you have described, I strongly feel this is the problem of expecting asynchronous function to behave synchronously,
await foreach(var book in bookList) {
var matches = new List < bookList > ();
if (bookList.All(book => ids.Contains(book.Id))) {
matches.Add(book);
}
return View("Index", matches.ToArray());
}
Try adding await before you call foreach loop. or better use for in loop
Thanks for your help everyone, the solution was actually to change this part of the ajax call to:
data: { ids: localStorage.getItem('videoIds') },
This code was tested in Visual Studio.
You have to create a viewModel:
public class IdsViewModel
{
public string[] Ids { get; set; }
}
Replace this:
var ids = JSON.parse(localStorage.getItem("bookIds"));
// returns: ["1", "2", "3"]
// or you can use
var ids = localStorage.getItem('videoIds'); //it still will be working
$.ajax({
type: "POST",
traditional: true,
url: '#Url.Action("Favourites", "Home")',
data: { ids: ids },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
with this
var ids= JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '/Home/Favourites',
data: { ids:ids },
success: function (result) {
....
and the action
public async Task <ActionResult> Favourites(IdsViewModel viewModel) {
var ids=viewModel.Ids;
.....

How to properly code Javascript / Ajax for use with Chart.js

I have a controller action in my MVC project that creates a json record with the components needed. This is working. The issue I am having is bringing it into a chart.js canvas. This will be a pie chart that shows all the related countries with a count of each. Json has this info. Originally this was setup to use google visualization but I want to use chart.js. I just started using it. Creating charts with static data is no issue but I am pulling the info from a SQL table and creating a json to read from.
I have tried using the same structure and calling the data: data[] but it doesn't work I have also tried data: getData, which is a var for the ajax function. I am getting the data per the council on refresh.
Here is my controller Action
public ActionResult CustomersByCountry()
{
CustomerEntities _context = new CustomerEntities();
var customerByCountry = (from c in _context.Addresses
group c by c.Country into g
orderby g.Count() descending
select new
{
Country = g.Key,
CountCustomer = g.Count()
}).ToList();
return Json(new { result = customerByCountry }, JsonRequestBehavior.AllowGet);
}
And here is the JavaScript/ajax - which is nested in a document.ready function with the rest of the charts.
EDIT - changed Ajax - Still not working
OrdersByCountry()
function OrdersByCountry() {
$.ajax({
url: '/admin/CustomersByCountry',
method: "GET",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (data) {
console.log (data);
var customer = $("#customerByCountryPieChart").get(0).getContext("2d");
console.log(customer)
var cpieChart = new Chart(customer, {
type: 'pie',
data: data,
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
}
});
};
Edit - The now working code is below.
I changed it to get states instead of country, just to clear up possible confusion. It made more sense to me to get States rather than Country at this point. This is working - meaning displaying the graph, I still need to work on the labels etc.
OrdersByStates()
function OrdersByStates() {
$.ajax({
url: '#Url.Action("CustomersByStates", "Admin")',
data: JSON,
contentType: "application/json; charset=utf-8",
method: "get",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (response) {
console.log(response);
var jsonresult = response
var labels = jsonresult.result.map(function (e) {
return e.State;
});
var data = jsonresult.result.map(function (e) {
return e.CountCustomer;
});;
var ctx = document.getElementById("CustomerByStatePieChart").getContext("2d");
var cpieChart = new Chart(ctx, {
type: 'pie',
data:
{
datasets: [
{
backgroundColor: ["#46BFBD", "#F7464A"],
hoverBackgroundColor: ["#5AD3D1", "#FF5A5E"],
label: "Orders",
data: data,
}]
},
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
}
});
};
});
try:
var cpieChart = new Chart(customer, {
type: 'pie',
data: data.result,
options: {
responsive: true,
title: {
display: true,
text: "Customers By Country",
}
}
});
the response from the server "data" var on your request is {result: LIST}

How to set serialization in Asp .Net Core

Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Importing JSON based remote data to Select2 using AJAX

The aim is to import data from the Controller side to a Select2 element (with multiselect toggled on). I want the setup to look something like the tags box in Stack Overflow, wherein you can begin typing a tag, select it, and select another one later.
I have been using the Select2 documentation as a reference, however the request isn't being sent to the Controller.
Select2 Documentation
My Code:
$(".jsData").select2({
ajax: {
contentType: 'application/json',
url: '<%=Url.Action("GetDataMethod","RelevantController")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
var datajs = $.map(data, function (obj) {
obj.text = obj.someterm; // desired field,
obj.id = obj.someId;
return obj;
});
return {
results: JSON.parse("[" + datajs.split(",") + "]")
};
}
},
multiple: true
});
I'm relatively new to bringing data dynamically to Select 2, so any help would be most appreciated. Thanks!
UPDATE: Found the solution, posting it here for others.
HTML
<input class="jsData" style="width: 100%" id="select2Data" ></input>
Javascript
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
contentType: 'application/json',
url: '<%=Url.Action("GetData","Controller")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
return {
results: $.map(JSON.parse(data), function (item) {
return {
text: item.term,
slug: item.slug,
id: item.Id
}
})
};
}
},
multiple: true
});

Select2 doesn't show the initSelection values

the jquery Select2(Version: 3.5.4) plugin doesn't show my initial value which I loaded on the initSelection function of the plugin. Here is my code:
$("#materialFieldTags").select2({
tags: true,
initSelection : function (element, callback) {
console.log(element);
console.log(callback);
var countryId = "3"; //Your values that somehow you parsed them
var countryText = "mater3";
var data = [];//Array
var tempJSONMat = {
materials: []
};
$.ajax({
url: "php/FormProcessing.php",
type: "post",
data: "main=" + "materialFault" + "&faultid="+ main.faultId,
dataType: 'json',
success: function(data){
data.forEach(function(column) {
//console.log(column);
tempJSONMat.materials.push({
"id" : column.material_id,
"text" : column.name
});
});
}
});
callback(tempJSONMat.materials[0]);
},
ajax: {
type: "POST",
url: 'php/FormFilling.php',
dataType: 'json',
data: function (params) {
return "main=" + "allMaterials" + "&searchterm=" + params;
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
};
})
};
},
cache: true
}
});
Can you take I look at my code? Because I can't see it!! I also have try the:
$("#materialFieldTags").select2("data",mydata);
After the initialization of the plugin, but I am getting the same result.
Finally, I found my mistake! It was define two element by the same id, by mistake! The data appeared on first one and I was looking the second one.

Categories