Add to javascript array dynamically - c#

I have a javascript file that for a slider that gets imag url's from an array. How can I add image url's from code behind. I want to get the pictures url from database so I want to add images to the array from code behind. I use asp.net c#. the jquery file is like below:
$(function() {
$('#ds_showcase').showcase({
linksOn: 'images',
css: {},
animation: { autoCycle: true, type: 'horizontal-slider', interval: 4000, stopOnHover:true, speed: 1500, easefunction: 'easeOutBounce'},
images: [
{ url: 'Showcase_ds_images/lift-truck.jpg ', description: 'Title 2', link: '', target: '_self' },
{ url: 'Showcase_ds_images/lifttruck2.jpg', description: 'Title 3', link: '', target: '_self' },
{ url: 'Showcase_ds_images/lift-truck3.jpg', description: 'Title 4', link: '', target: '_self' },
],
navigator: { position: 'bottom-right', orientation: 'horizontal', autoHide: false, showNumber: false,
css: { padding: '10px'},
item: { css: { height: '10px', width: '10px', backgroundColor: '#cccccc', borderColor: '#999999'},
cssHover: { backgroundColor: '#3399ff'},
cssSelected: { backgroundColor: '#3399ff', borderColor: '#3399ff'}
}
}
});
});

You can always do something like this:
var jsArr = [];
<%foreach(string img in images){%>
jsArr.push('<%=img%>');
<%}%>
This code will generate the js with hardcoded strings from the server.
The js each client will see will be something like this:
var jsArr = [];
jsArr.push('http://server/img1.png');
jsArr.push('http://server/img2.png');
jsArr.push('http://server/img3.png');
In your case - Something like this:
$(function() {
var jsArr = [];
<%foreach(Image img in images){%>
jsArr.push({url: '<%=img.url%>', description: '<%=img.desc%>', link: '', target:'_self'});
<%}%>
$('#ds_showcase').showcase({
linksOn: 'images',
css: {},
animation: { autoCycle: true, type: 'horizontal-slider', interval: 4000, stopOnHover:true, speed: 1500, easefunction: 'easeOutBounce'},
images: jsArr,
navigator: { position: 'bottom-right', orientation: 'horizontal', autoHide: false, showNumber: false,
css: { padding: '10px'},
item: { css: { height: '10px', width: '10px', backgroundColor: '#cccccc', borderColor: '#999999'},
cssHover: { backgroundColor: '#3399ff'},
cssSelected: { backgroundColor: '#3399ff', borderColor: '#3399ff'}
}
}
});
});

Related

Problem while uploading 10000 data to Devextreme datagrid in ASP.NET MVC

I am using devextreme datagrid in asp.net Mvc. Datagrid works fine when I am processing 5000 data. But when I want to process with 10000 data, it cannot load the data and the internal server gives an error.
My index.cshtml;
<div class="row">
<div class="col-lg-12">
<h1 class="page-header col-dark-green">
Barsan Portal <small>Gönderici/Alıcı</small>
</h1>
<div class="demo-container">
<div id="gridContainer" style="height:800px"></div>
</div>
</div>
</div>
My index.js :
$(function () {
var dataSource = new DevExpress.data.DataSource("/Nakliye/GetGondericiAlicilar");
console.log(dataSource);
$("#gridContainer").dxDataGrid({
dataSource: new DevExpress.data.CustomStore({
key: "kodu",
pageSize:50,
loadMode: "raw", // omit in the DataGrid, TreeList, PivotGrid, and Scheduler
load: function () {
return $.getJSON("/Nakliye/GetGondericiAlicilar")
.fail(function () { throw "Data loading error" });
}
}),
selection: {
mode: 'multiple'
},
renderAsync: true,
allowColumnReordering: true,
allowColumnResizing: true,
cellHintEnabled: false,
columnResizingMode: "nextColumn",
showBorders: true,
searchPanel: {
visible: true,
width: 240,
placeholder: "Ara..."
},
headerFilter: {
visible: true,
},
filterPanel: {
visible: true
},
filterRow: {
visible: true
},
loadPanel: {
enabled: true
},
groupPanel: {
visible: true,
placeholder: "Bir sütun başlığını o sütuna göre gruplandırmak için buraya sürükleyin"
},
pager: {
showPageSizeSelector: true,
allowedPageSizes: [10, 20, 50, 100, 200],
showNavigationButtons: true,
showInfo: true,
infoText: "Sayfa {0} / {1} ({2} öğe)"
},
columns: [{
dataField: "adi",
caption: "Adı"
}, {
dataField: "Adres",
}, {
dataField: "il",
width: 115,
caption: "İl"
}, {
caption: "Ülke",
dataField: "ulke",
}, {
caption: "Posta Kodu",
dataField: "postakodu",
width: 115,
}, {
caption: "Telefon",
dataField: "telefon",
width: 155,
}, {
caption: "Faks",
dataField: "faks",
width: 155,
}, {
caption: "İlgili",
dataField: "ilgili",
width: 195,
}]
});
});
My controller about action:
public ActionResult GetGondericiAlicilar() { return Json(_nakliyeService.GetGondericiAlicilar(), JsonRequestBehavior.AllowGet); }
GetGondericiAliciler() in My service :
public List<gnladresbankasi> GetGondericiAlicilar()
{
var result = _objectRawSql.Execute(StaticParams.Connstr, typeof(gnladresbankasi),
//sql functions
#"Select top 10000 kodu, adi, adres1 + ' ' + adres2 AS Adres, il, (select adi from gnlulke where kod = ulke) AS Ulke, postakodu, telefon, fax, ilgili
FROM gnladresbankasi ab WHERE Exists(select * from gnlFirmaGondericiAlici ga WHERE ab.kodu = ga.GondericiAliciKodu)").Cast<gnladresbankasi>().ToList();
return result;
}
As I mentioned, 5000 data works well, but when there is 10000 data, the loading icon returns and the data is not loaded.
Should a special action be taken regarding big data?
I found the following error in the browser network tab;
Server Error in '/' Application.
Error while serializing or deserializing using JSON JavaScriptSerializer. The length of the string exceeds the value set in the maxJsonLength property.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Can I set an unlimited length for maxJsonLength in web.config this solved my problem.

jqGrid not showing json data in MVC

jqGrid is not showing json data fetched from MVC controller, it also has a emptyrecords label which is also not visible in this case. Here is my jQuery code-
$(function () {
$("#JQGrid1").jqGrid({
url: "/CertificateDetails/GetCertificateDetails",
datatype: 'json',
mtype: 'Get',
colNames: ['Name', 'Issuer', 'Location', 'Private Key[Yes/No]'],
//data: dataArray,
colModel: [
{
key: false,
name: 'Name',
index: 'Name',
editable: false
},
{
key: false,
name: 'Issuer',
index: 'Issuer',
editable: false
},
{
key: false,
name: 'Location',
index: 'Location',
editable: false
},
{
key: false,
name: 'HasPrivateKey',
index: 'HasPrivateKey',
editable: false
}
],
height: '100%',
viewrecords: true,
caption: "Certificate Details",
emptyrecords: "No record to display!!"
});
});
Controller code:
CertDetails cd = new CertDetails();
public ActionResult Index()
{
return View();
}
//
// GET: /CertificateDetails/
public ActionResult GetCertificateDetails()
{
var stores = new Dictionary<StoreName, string>()
{
{StoreName.My, "Personal"},
{StoreName.Root, "Trusted roots"},
{StoreName.TrustedPublisher, "Trusted publishers"},
{StoreName.AddressBook, "Address Book"},
{StoreName.AuthRoot, "Auth Root"},
{StoreName.CertificateAuthority, "Certificate authority"},
{StoreName.Disallowed, "Disallowed"},
{StoreName.TrustedPeople, "Trusted people"}
// and so on
}.Select(s => new { store = new X509Store(s.Key, StoreLocation.LocalMachine), location = s.Value }).ToArray();
foreach (var store in stores)
store.store.Open(OpenFlags.ReadOnly); // open each store
var list = stores.SelectMany(s => s.store.Certificates.Cast<X509Certificate2>()
.Select(mCert => new CertDetails
{
HasPrivateKey = mCert.HasPrivateKey ? "Yes" : "No",
Name = mCert.FriendlyName != "" ? mCert.FriendlyName : "Unavailable",
Location = s.location,
Issuer = mCert.Issuer
})).ToList();
return Json(list,JsonRequestBehavior.AllowGet);
}
Here is the data returned from controller action method-
[{"Name":"Unavailable","HasPrivateKey":"Yes","Location":"Personal","Issuer":"CN=Dell Issuing Certificate Authority 302, OU=MS PKI, O=Dell Inc."},{"Name":"IIS Express Development Certificate","HasPrivateKey":"Yes","Location":"Personal","Issuer":"CN=localhost"}]
I'm getting the data in JSON format from the controller but neither jqGrid shows any data nor it shows empty records label. Any idea how to solve this issue?
You can try jQuery DataTable plugin instead, like below:
$(document).ready(function () {
$("#myGrid").dataTable({
"ajax": {
"url": "/CertificateDetails/GetCertificateDetails",
"dataSrc": ""
},
"columns": [{
"data": "Name"
}, {
"data": "Location"
}, {
"data": "Issuer"
}, {
"data": "HasPrivateKey"
}]
});
});
<table id="myGrid">
<thead>
<tr style="text-align:left;">
<th>Name</th>
<th>Location</th>
<th>Issuer</th>
<th>HasPrivateKey?</th>
</tr>
</thead>
</table>
Don't forget to add the references-
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>

How to display an image in the column of jqgrid

I want to display a image in the column of jqgrid for all data I get from '/Index/CaseBatchDetailList'. i have my jquery like,
$(function () {
var outerwidth = $('#TableCaseDtlsView').width();
$("#CaseBatchDetailList").jqGrid({
url: '/Index/CaseBatchDetailList',
datatype: 'json',
mtype: "GET",
colNames: ["Serial Number", "Denomination", "Note Image", "Back Image"],
colModel: [
{ name: "serialno", sortable: true, width: "120px", align: "center" },
{ name: "denomination", sortable: true, width: "120px", align: "left" },
{
name: "frontimageurl", sortable: false, width: "290px", align: "center", fixed: true,
formatter: function () {
return "<img src = /F:/MCP_Images/635101007551068098_324.jpg>";
}
},
{
name: "backimageurl", sortable: false, width: "290px", align: "center", fixed: true,
formatter: function () {
return "<img src = /F:/MCP_Images/635101007551068098_324.jpg>";
}
}
],
...
});
i just tried with the example for img src. I need to display the different images in different columns. As iam the beginner i dont know how to manipulate this.Kindly tell me how to achieve this.
As i saw your comment that you are having the image source in the list, then within your formatter you can do this:
formatter: function (cellvalue, options, rowobject) {
return "<img src='"+cellvalue+"'>";
}

Uncaught TypeError: undefined is not a function - Highcharts - MVC

I'm trying to use Highcharts in my MVC web application. I have loaded all the prerequisites to make Highcharts working. But apparently, "highchart" is still not recognized by the page. I'm checking the rendered page by google developer tool and it says all the JQuery and Highchart javascript files are loaded properly. Any help?
This is my .cshtml code:
#using System.Web.Optimization
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Highcharts-4.0.1/js/highcharts.js")
#Scripts.Render("~/Scripts/Highcharts-4.0.1/js/modules/exporting.js")
<script type="text/javascript">
$(function() {
var chart;
debugger;
$(document).ready(function() {
debugger;
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
});
</script>
}
So this does the trick (which is kind of weird!) :
I need to change this line:
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
To this line:
chart = new Highcharts.Chart({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
renderTo: 'container'
},
This is the link which helped me through: http://developmentpassion.blogspot.com/2013/09/bar-charts-and-graphs-in-aspnet-mvc.html

JqGrid is displayed with columns and no json data

i am trying to bind JSON data to jqgrid. But, i am not getting any data.
here, is my code:
$(function () {
$("#list").jqGrid({
url:'<%:Url.Action("LoadData","Home")%>',
datatype: "JSON",
mtype: "GET",
colNames: ["sid","sname"],
colModel: [
{ name: "sid", width: 55,align:"center"},
{ name: "sname", width: 90,align:"center"},
],
jsonReader: {
repeatitems: false
},
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
autoencode: true,
caption: "My first grid"
});
});
I am using it in Asp.net MVC Application.
I am able to hit the controller and get the JSON data..but i was unsucessful in displaying data to grid.
I am getting proper json o/p from controller.
My Controller is:
public JsonResult LoadData()
{
var Data= new DataTable();
Data= DataModel.LoadData();
var JsonData = JsonConvert.SerializeObject(Packages, Formatting.Indented);
return Json(new
{
JsonData
}, JsonRequestBehavior.AllowGet);
}
I think there is error in my JQgrid jquery code. Firtly, i want to implement the jqgrid with minimal configuration.
The JSON response i am getting is:
[
{
"sid": 2,
"sname": "ABC"
},
{
"sid": 3,
"sname": "XYZ"
},
{
"sid": 4,
"sname": "CBA"
},
{
"sid": 5,
"sname": "IIT"
},
{
"sid": 6,
"sname": "NIT"
}
]
This is my HTML Structure:
<table id="list">
</table>
<div id="pager"></div>
I removed the duplicates from the data i am fetching..
The JSON result, i have checked in Text Visualizer of Visual Studio.Its fine..
Please help..
I suppose that the reason of your problem is the usage of JsonConvert.SerializeObject. You should return object instead of string. Try to use
return Json(Packages, JsonRequestBehavior.AllowGet);
directly.
Not sure you have js code in .js file on in .aspx file.
Anyway try this and check the request/response with Firefox/Chrome console
$(function () {
$("#list").jqGrid({
url:/Home/LoadData/,
datatype: "json",
mtype: "GET",
colNames: ["sid","sname"],
colModel: [
{ name: "sid", width: 55,align:"center"},
{ name: "sname", width: 90,align:"center"},
],
pager: "#pager",
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
caption: "My first grid"
});
});
HTML
<table id="list"></table>
<div id="pager"></div>

Categories