How to avoid ISPOSTBACK in an asp.net jquery(ajax) application? - asp.net

I have an ASP.NET WEB API application using jquery/Ajax. When I select "M1" in my dropdownlist a gridview shows data for Machine 1, when I click "update" button. If change to "M2", the gridview show data for M1 AND M2. It continue to add data. I only want to see data for M1 or M2 and so on. The problem is probadly due to POSTBACK function. How to solve this? Update panel?
function update() {
$.ajax({
type: 'GET',
url: '/api/stop/',
dataType: "JSON",
data: "data",
success: function (data) {
$.each(data, function (i, data) {
if (data.machinename == $("#DropDownList11").val() && data.name != $(null).val() && data.overlimit == 1 && data.stopcause ==$(null).val())
{
var _id = data.id;
var _machinename = data.machinename;
var _stopcause = data.stopcause;
var _machinename = data.machinename;
var _name = data.name;
var _stop1 = data.idlestart;
var _stop2 = data.idlestop;
var _data = '<tr><td>' + _id + ' </td><td>' + _machinename + '</td><td>' + _name + '</td><td>' + _stop1 + '</td><td>' + _stop2 + '</td><td>';
var _data2 = '<option>' + data.id + '</option>'
$('table').append(_data);
$('#DropDownList5').append($(_data2))
};
});
}
});
}

Well, My Guess is, the problem is in your append logic, $('table').append(_data);. You keep on appending your data to the table and not clearing the previous ones. Just try to clear the data before going in the $.each api of jQuery. Something like below:
$.ajax({
type: 'GET',
url: '/api/stop/',
dataType: "JSON",
data: "data",
success: function (data) {
$("table tr").remove(); // this line will clear off the previous table tr elements before appending new ones.
$.each(data, function (i, data) {
if (data.machinename == $("#DropDownList11").val() && data.name != $(null).val() && data.overlimit == 1 && data.stopcause ==$(null).val())
{
var _id = data.id;
var _machinename = data.machinename;
var _stopcause = data.stopcause;
var _machinename = data.machinename;
var _name = data.name;
var _stop1 = data.idlestart;
var _stop2 = data.idlestop;
var _data = '<tr><td>' + _id + ' </td><td>' + _machinename + '</td><td>' + _name + '</td><td>' + _stop1 + '</td><td>' + _stop2 + '</td><td>';
var _data2 = '<option>' + data.id + '</option>'
$('table').append(_data);
$('#DropDownList5').append($(_data2))
};
});
}
});
Moreover, I am not sure where is the POSTBACK function that you are mentioning, as best of my knowledge, POSTBACK functions are part of WebForms and not WebAPIs. So, I assume you by POSTBACK method you meant the method success.

Related

Add 10 days with selected date -on-change method -service now

I have 2 date fields issued date and due date.When I choose issued date,due date should be auto populated by adding 10days with selected date. I have written on-change method for this
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
//var issuedDate=new GlideDateTime(g_form.getValue('u_issued_date'))
//var issuedDate=g_form.getValue('u_issued_date')
alert(issuedDate)
var gdt = new GlideDateTime(issuedDate);
gdt.addDays(10)
g_form.setValue('u_due_date',gdt);
}
I am getting an error GlideDateTime is not defined function ().How can I achieve this? Is there any other way?
GlideDateTime is not available on client side. For simple operation like the one you are having you can use javascript Date object. Which is pain to format, but doable, example:
var date = new Date(g_form.getValue('u_issued_date'));
date.setDate(date.getDate() + 10); //add 10 days
g_form.setValue('u_due_date', formatDate(date));
function formatDate (date) {
return date.getFullYear() + '-' +
leadingZero(date.getMonth() + 1) + '-' +
leadingZero(date.getDate()) + ' ' +
date.getHours() + ':' +
date.getMinutes() + ':' +
date.getSeconds();
}
function leadingZero (value) {
return ("0" + value).slice(-2);
}
For more complicated operation you would wish GlideDateTime you will have to use GlideAjax, that will do operations on server side, and provide result.

how do I replace the text "rows" in pagination

In the pagination example, how do I replace the text at the bottom, "rows" with another word e.g. "products"?
Showing 1 to 10 of 800 rows
becomes
Showing 1 to 10 of 800 products
Ported from issue # 882 on bootstrap-table's issue tracker.
This text is part of bootstrap-table's localizations. English (en-US) is loaded by default.
Solution # 1
Create and include a custom locale
/js/locale/bootstrap-table-en-US-custom.js
(function ($) {
'use strict';
$.fn.bootstrapTable.locales['en-US-custom'] = {
formatLoadingMessage: function () {
return 'Hold your horses...';
},
formatRecordsPerPage: function (pageNumber) {
return pageNumber + ' bananas per page';
},
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return 'Showing ' + pageFrom + ' to ' + pageTo + ' of ' + totalRows + ' products';
},
formatSearch: function () {
return 'Search';
},
formatNoMatches: function () {
return 'No matching records found';
},
formatPaginationSwitch: function () {
return 'Hide/Show pagination';
},
formatRefresh: function () {
return 'Refresh';
},
formatToggle: function () {
return 'Toggle';
},
formatColumns: function () {
return 'Columns';
},
formatAllRows: function () {
return 'All';
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US-custom']);
})(jQuery);
It is also important to note, that the localization settings get merged in to the table settings -meaning that you can simply
Solution # 2 Pass them as an argument in your table settings:
$('#table').bootstrapTable({
// .. your other table settings
pagination: true,
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return 'Showing ' + pageFrom + ' to ' + pageTo + ' of ' + totalRows + ' rows';
}
});
or you can
var $table = $('#bootstrap-table');
$table.bootstrapTable({
toolbar: ".toolbar",
clickToSelect: true,
showRefresh: true,
search: true,
showToggle: true,
showColumns: true,
pagination: true,
searchAlign: 'left',
pageSize: 8,
clickToSelect: false,
pageList: [8,10,25,50,100],
formatRecordsPerPage: function(pageNumber){
return pageNumber + " rows visible";
},
formatShowingRows: function(pageFrom, pageTo, totalRows){
//do nothing here, we don't want to show the text "showing x of y from..."
return 'Showing ' + pageFrom + ' to ' + pageTo + ' of ' + totalRows + ' ';
}
});
based on jtrumbull`s totally correct answer, I would spent a third one:
Solution # 3 use a locale and merge / overwrite parts of them with your own:
in this example, we will overwrite the already defined "formatShowingRows" function.
// create an array where you store your own translations
var mylocale = {
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return 'Ergebnisse <b>' + pageFrom + '-' + pageTo + '</b> von <b>' + totalRows + '</b>';
}
}
// extend the used locale
$.extend(true, $.fn.bootstrapTable.locales.de, mylocale);

Asp.net webform with flot.js chart on return Json does not work

I am using ASP.NET webforms for flot charts I connected to database in test.aspx.cs file using [Webmethod] where I can return json.
I stored the return value both in textarea and $.plot(placeholder, [and also here], options) It does not print the graph in placeholder however when I do:
var data = past
the value of textarea here and run applicationn it prints to me the value.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetLocation(string location)
{
List<string> result = new List<string>();
StringBuilder strQuery = new StringBuilder();
strQuery.Append("SELECT Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica) AS SDay, COUNT(Statistiche.ID_Tabella) AS Stats");
strQuery.Append(" FROM Statistiche INNER JOIN Tabelle ON Statistiche.ID_Tabella = Tabelle.ID_Tabella INNER JOIN");
strQuery.Append(" Location ON Statistiche.ID_Colonna_Statistica = Location.ID_Location");
strQuery.Append(" WHERE (Statistiche.ID_Tabella = 2) AND (Statistiche.ID_Box = 60) AND (Location.Nome_Location = 'Albilò')");
strQuery.Append("GROUP BY Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica)");
string query = strQuery.ToString();
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int counter = 1;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (counter == 1)
{
result.Add("[{'label': 'Europe (EU27)','data':[[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
}
else
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
if (counter==31)
{
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]]}]");
}
counter++;
}
return result;
}
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test.aspx/GetLocation",
data: "{'location':'Albilò'}",
success: function drawChart(msg) {
var options = { lines: { show: true }, points: { show: true }, xaxis: { tickDecimals: 0, tickSize: 1} };
var ddata = [];
var data = msg.d;
for (var i = 0; i < 32; i++) {
ddata.push(data[i]);
}
var placeholder = $("#placeholder");
$("#txtvalue").val(ddata);
var datad = $("#txtvalue").text();
$.plot(placeholder, ddata, options);
},
error: function () {
alert("call is called111");
}
});
First of all, why do you create JSON yourself? You've already specified to return JSON in you attributes.
Refactore method to return simple array of POCO objects like
[Serializable]
public class pocoObject
{
public string Label;
..
}
Then your method should just return list of object and have attributes set up:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<pocoObject> GetLocation(string location)
{
...
return result; // result is list of pocoObjects
}
Flot.js is rather sensitive to data you set as source, so after this take a look at data in firebug, it should be correct json formatted data. So please visit wiki and also compare your data to working samples.
This how you can initiliaze legend names of you plot:
$(function () {
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d1.push([i, Math.sin(i)]);
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d2.push([i, Math.cos(i)]);
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.1)
d3.push([i, Math.tan(i)]);
$.plot($("#placeholder"), [
{ label: "sin(x)", data: d1},
{ label: "cos(x)", data: d2},
{ label: "tan(x)", data: d3}
], {
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]
},
yaxis: {
ticks: 10,
min: -2,
max: 2
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] }
}
});
});

web grid server pagination trigger multiple controller call when changing page

When I server-filter on "au" my web grid and change page, multiple call to the controller are done :
the first with 0 filtering,
the second with "a" filtering,
the third with "au" filtering.
My table load huge data so the first call is longer than others.
I see the grid displaying firstly the third call result, then the second, and finally the first call (this order correspond to the response time of my controller due to filter parameter)
Why are all that controller call made ?
Can't just my controller be called once with my total filter "au" ?
What should I do ?
Here is my grid :
$("#" + gridId).kendoGrid({
selectable: "row",
pageable: true,
filterable:true,
scrollable : true,
//scrollable: {
// virtual: true //false // Bug : Génère un affichage multiple...
//},
navigatable: true,
groupable: true,
sortable: {
mode: "multiple", // enables multi-column sorting
allowUnsort: true
},
dataSource: {
type: "json",
serverPaging: true,
serverSorting: true,
serverFiltering: true,
serverGrouping:false, // Ne fonctionne pas...
pageSize: '#ViewBag.Pagination',
transport: {
read: {
url: Procvalue + "/LOV",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8"
},
parameterMap: function (options, type) {
// Mise à jour du format d'envoi des paramètres
// pour qu'ils puissent être correctement interprétés côté serveur.
// Construction du paramètre sort :
if (options.sort != null) {
var sort = options.sort;
var sort2 = "";
for (i = 0; i < sort.length; i++) {
sort2 = sort2 + sort[i].field + '-' + sort[i].dir + '~';
}
options.sort = sort2;
}
if (options.group != null) {
var group = options.group;
var group2 = "";
for (i = 0; i < group.length; i++) {
group2 = group2 + group[i].field + '-' + group[i].dir + '~';
}
options.group = group2;
}
if (options.filter != null) {
var filter = options.filter.filters;
var filter2 = "";
for (i = 0; i < filter.length; i++) {
// Vérification si type colonne == string.
// Parcours des colonnes pour trouver celle qui a le même nom de champ.
var type = "";
for (j = 0 ; j < colonnes.length ; j++) {
if (colonnes[j].champ == filter[i].field) {
type = colonnes[j].type;
break;
}
}
if (filter2.length == 0) {
if (type == "string") { // Avec '' autour de la valeur.
filter2 = filter2 + filter[i].field + '~' + filter[i].operator + "~'" + filter[i].value + "'";
} else { // Sans '' autour de la valeur.
filter2 = filter2 + filter[i].field + '~' + filter[i].operator + "~" + filter[i].value;
}
} else {
if (type == "string") { // Avec '' autour de la valeur.
filter2 = filter2 + '~' + options.filter.logic + '~' + filter[i].field + '~' + filter[i].operator + "~'" + filter[i].value + "'";
}else{
filter2 = filter2 + '~' + options.filter.logic + '~' + filter[i].field + '~' + filter[i].operator + "~" + filter[i].value;
}
}
}
options.filter = filter2;
}
var json = JSON.stringify(options);
return json;
}
},
schema: {
data: function (data) {
return eval(data.data.Data);
},
total: function (data) {
return eval(data.data.Total);
}
},
filter: {
logic: "or",
filters:filtre(valeur)
}
},
columns: getColonnes(colonnes)
});
Here is my controller :
[HttpPost]
public ActionResult LOV([DataSourceRequest] DataSourceRequest request)
{
return Json(CProduitsManager.GetProduits().ToDataSourceResult(request));
}
The 3 correspond to the initial load (no filtering) and the following ones as you type in the condition of filter, similar in kendoAutocomplete but in kendoAutocomplete there are a couple of options (time and min length) that control when to send the requests (I couldn't find anything similar in grid).
If your problem is loading a huge amount of data I do recommend limiting the size of the data transmitted using pageSize in the DataSource definition. But, obviously, this is not a solution if what takes long is executing the query.
In such scenarios it is recommended to create a typing delay and thus perform a request when the user has stopped typing (unless he is typing slower than regular typing).
To create a delay I can suggest you the following:
<script type="text/javascript">
var globalTimeout = null;
$('#searchInput').keyup(function () {
if (globalTimeout != null) clearTimeout(globalTimeout);
globalTimeout = setTimeout(SearchFunc, 500);
});
function SearchFunc(){
globalTimeout = null;
$('#yourGridName').data('kendoGrid').dataSource.filter({ field:"theField",operator:"startswith",value:$('#searchInput').val() })
}
</script>

Extjs4 multigrouping header value css

I am using the Extjs4 multigrouping plugin from here.
I have used it successfully, however i want to show the summary of the totals of each column within the group header itself . how do i set up the appropriate CSS for that ?
In Multigrouping.js
getFragmentTpl: function() {
var me = this;
return {
indentByDepth: me.indentByDepth,
depthToIndent: me.depthToIndent,
renderGroupHeaderTpl: function(values, parent) {
return Ext.XTemplate.getTpl(me, 'groupHeaderTpl').apply(values, parent);
//var z = new Ext.XTemplate('{name} ({rows.grouplength})');
//return z.apply(values, parent);
}
};
},
In my grid
features: [
{
ftype:'multigrouping',
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
debugger;
var sum1 =0 ,sum2=0,sum3=0;
for( var i = 0 ; i< values.records.length ; i++)
{
var val = parseFloat(values.records[i].data.d2012.mp);
sum1 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2013.mp);
sum2 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2014.mp);
sum3 += isNaN(val) ? 0.0 : val;
}
return values.name + '(' + values.records.length + ')' + ' ' + sum1.toFixed(2) + ' ' + sum2.toFixed(2) + ' ' + sum3.toFixed(2);
}
}
]
},
had to resort to a few hacks to get this to work. still waiting on an official answer.
The main reason i had to do this and not use the multigrouping summary is because
- i want to limit the number of records from the server. I can do some smart grouping of
my business objects at the server side.
- the main reason to do this is because of IE8's performance on larger sets of data.
- had already tried the extjs4 tree grid component which works well on chrome but had performance issues on IE8.
the hack is to
a) use an array property in the grid to store the dom elements which i want to manipulate
b) use a boolean to know when the layout is completed the first time
b) add listeners for afterlayout ( when your app can do an Ext.get('..dom element..') you know you are done )
The listener :
listeners :
{
afterlayout : function(eopts)
{
var x = this.mOwnArray;
if(!this.loadedwithVals && x.length > 0)
{
for(var i =0 ; i<x.length ; i++)
{
var dom = Ext.get(x[i].id);
var theId = dom.id;
theId = theId.match(/\d+/)[0];
var title = dom.query("td[class='x-grid-cell x-grid-cell-first']");
title[0].className = 'x-grid-cell x-grid-cell-gridcolumn-' + theId + ' x-grid-cell-first';
title[0].colSpan=1;
var groupedHeader = dom.query("div[class='x-grid-group-title']");
groupedHeader[0].innerHTML = x[i].name + '(' + x[i].length + ')';
for(var year=2012;year<=2018;year++)
{
var t = "t"+year;
var someText1 = '<td class=" x-grid-cell x-grid-cell-numbercolumn">';
var someText2 = '<div class="x-grid-cell-inner " style="text-align: left; ;">';
var someText3 = '<div class="x-grid-group-title">' + x[i].total[t] + '</div></div></td>';
var someText = someText1 + someText2 + someText3;
dom.insertHtml("beforeEnd",someText);
}
}
this.loadedwithVals = true;
}
}
And the feature as in
features: [
{
ftype:'multigrouping',
startCollapsed : true,
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
var header = new Object();
header.id = values.groupHeaderId;
header.sum = [];
header.total = new Object();
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
header.total[t] = [];
}
// all the records in this header
for( var i = 0 ; i< values.records.length ; i++)
{
// for all the 'years' in this record
for(var year=2012;year<=2018;year++)
{
var d = "d"+year;
var ct = "t" + year;
var arecord = values.records[i].data;
var val = parseFloat(arecord[d].mp);
val = isNaN(val) ? 0.0 : val;
Ext.Array.push(header.total[ct],val);
}
}
// push the sum of the records into its top level group
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
var sum = Ext.Array.sum(header.total[t]);
header.total[t] = sum.toFixed(2);
}
header.name = values.name;
header.length = values.records.length;
var headerName = values.name;
if(values.hasOwnProperty('parent'))
{
var parent = values.parent;
headerName = headerName.replace(parent,'');
}
header.name = headerName;
header.length = values.records.length;
Ext.Array.push(grid.mOwnArray,header);
// really not used
return values.name + '(' + values.records.length + ')';
}
}
]
},
]

Resources