Passing Data to client side (javascript) in post back in .ascx page - javascript

There is devExpress dxchart in ascx page.
asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<br />
<div id="trendChart" style="height: 500px; width: 100%;"> </div>
<br />
</ContentTemplate>
</asp:UpdatePanel>
Data is loading fine in Page_Load method. But when button click is used and chart data is not getting updated. It shows old values as were in Page_Load.In button click following code is used.
NewData = jsonData
System.Web.UI.ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "ANY_KEY" +
Guid.NewGuid.ToString, "UpdateChart();", True)
'NewData' is public property. The UpdateChart in javascript is below.
function UpdateChart()
{
myData = '<%= NewData%>';
alert('tesing');
var parseObj = JSON.parse(myData);
$(function () {
$("#trendChart").dxChart({
dataSource: parseObj,
series: {
argumentField: "Month",
valueField: "Value",
name: "Value",
type: "bar",
color: '#ffaa66'
}
});
});
}
when button click is done 'NewData' is nothing in UpdateChart() (javascript) and chart still shows old values.

You could pass the data as a property of the UpdateChart-function and then some other adjustments to your code.
First create an init-dxChart-function. This function can be called on first load of page and when you update your data.
function InitChart(dataForChart) {
$("#trendChart").dxChart({
dataSource: dataForChart,
series: {
argumentField: "Month",
valueField: "Value",
name: "Value",
type: "bar",
color: '#ffaa66'
}
});
}
Second change your UpdateChart-function, so that it gets a parameter:
function UpdateChart(myData) {
var parsedData = JSON.parse(myData);
// Call Init Chart function here
InitChart(parsedData);
}
Third: Change your server-side-javascript, so the data is passed to the function:
System.Web.UI.ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "ANY_KEY" +
Guid.NewGuid.ToString, "UpdateChart(" + jsonData + ");", True)

Related

Unable to redirect and call a function when clicked on hyperlink

I have setup a kendo grid. The gird has a column containing a hyperlink. When I click on the link, I need to call a function and then I need to redirect to a new page. I know it sounds simple. I have a stand alone example which is doing same.
But when I try to use same logic in kendo grid, I am unable to get the desired result. Please help. Here is a link to Kendo Grid with a column containing hyperlink.
$('#one').kendoGrid({
dataSource: dataOne,
columns: [{
field: 'a',
template: "<a onclick=return doWork() href='/home/again/${a}'>${a}</a>"
}, {
command: 'destroy'
}],
editable: {
confirmation: false
}
});
try this soution
Add this function before grid settings:
function showFoo() {
alert('I am foo!');
return true;
}
Add following code at the end (after grid settings).
var el = document.getElementById('foo');
el.onclick = showFoo;
You need prevent the default click by event.preventDefault() and then redirect.
$('#one').kendoGrid({
dataSource: dataOne,
columns: [{
field: 'a',
template: "<a onclick=\"doWork(event, '/home/again/${a}')\" href=''>${a}</a>"
}, {
command: 'destroy'
}],
editable: {
confirmation: false
}
});
function doWork(ev, url){
ev.preventDefault();
alert("redirecting");
//... do your works
window.location.href = url;
}

ASP.Net - Invalid Json String

I have been developing a web application in ASP.Net, which should return information from a database via a Web Service class.
From there, I wish to bind the data to a Google Combo chart.
The data can be bound to a grid view, so I know the method to call from the database is working, but when I try to bind it to the chart I receive the error message:
Invalid Json String:
!Doctype HTML
html lang = "en"
This is my first time working with javascript, so I assume that my javascript methods are accessing the wrong data, but I'm not sure where I'm going wrong.
If anybody could let me know what I have done wrong, it would be appreciated.
DEFAULT.ASPX
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var jsonData = $.ajax({
url: "Default.aspx/GetChartData",
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Chart Title',
vAxis: { title: 'Scores %' },
hAxis: { title: 'Counties' },
seriesType: 'bars',
series: {
2: {
targetAxisIndex: 1
},
vAxes: {
1: {
title: '1',
textStle: { color: 'red' }
}
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<asp:GridView ID="Grid1D" runat="server"
AutoGenerateColumns = "true" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
PageSize = "10" Caption = "1-Dimensional Array">
</asp:GridView>
<div id ="chart_div" style="width:500px;height:400px"></div>
<asp:Literal ID="ltScripts" runat="server"></asp:Literal>
</body>
</html>
Sounds a lot like your call to Default.aspx/GetChartData returns an error page from the IIS that is hosting it. You should take a look at your jsonData variable, as it is anything but json.

load jqGrid on button click but it fails on second time

I'm using jqGrid to display data from database. There are 2 textboxes to input the criteria. After inputting the criteria and clicking the Show button, jqGrid is shown to the page.
The second time I clicked the Show button with a different set of criteria entered nothing happens. It still shows data from the first click. How do I solve this?
View:
#section styles {
<link href="~/Content/themes/redmond/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
}
<h2>Index</h2>
<p class="form-inline">
Ext: <input type="text" class="form-control" id="extUsed" />
Date: <input type="text" class="form-control" id="startOfCall" readonly="readonly" />
<button class="btn btn-primary" id="btnShow">Show</button>
</p>
<table id="grid"></table>
<div id="pager"></div>
#section scripts {
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script>
var firstClick = true;
$(function () {
$("#startOfCall").datepicker();
$("#btnShow").click(function (e) {
e.preventDefault();
if (!firstClick) {
$("#grid").trigger("reloadGrid");
} else {
$("#grid").jqGrid({
mtype: "GET",
url: "#Url.Content("~/CallTransaction/GetCallTransactionList")",
datatype: "json",
colNames: ["Ext Used", "Start of Call", "Destination Number"],
colModel: [
{ name: "ExtUsed", index: "ExtUsed" },
{ name: "StartOfCall", index: "StartOfCall", formatter: "date", formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' } },
{ name: "DestinationNumber", index: "DestinationNumber" }
],
postData: {
"CallTransaction.ExtUsed": $("#extUsed").val(),
"CallTransaction.StartOfCall": $("#startOfCall").val()
},
pager: jQuery("#pager"),
rowNum: 10,
rowList: [10, 25, 50],
height: "100%",
caption: "Call Transaction",
autowidth: true,
//sortname: "ExtUsed",
sortable: true,
viewrecords: true,
emptyrecords: "No records to display",
});
$("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
}
firstClick = false;
});
});
</script>
}
Controller:
public JsonResult GetCallTransactionList(CallTransaction callTransaction, string sidx, string sord, int page, int rows)
{
int pageIndex = page - 1;
int pageSize = rows;
var callTransactionResult = db.Search(callTransaction);
int totalRecords = callTransactionResult.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
callTransactionResult = callTransactionResult.OrderByDescending(ct => ct.ExtUsed).ToList();
callTransactionResult = callTransactionResult.Skip(pageIndex * pageSize).Take(pageSize).ToList();
}
else
{
callTransactionResult = callTransactionResult.OrderBy(ct => ct.ExtUsed).ToList();
callTransactionResult = callTransactionResult.Skip(pageIndex * pageSize).Take(pageSize).ToList();
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = callTransactionResult
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
It's important to understand that the current code set one value of postData during creating the grid. The value of postData parameter will be object with properties evaluated at the moment of creating of the grid.
To fix the code you need use function as the value of postData properties:
postData: {
"CallTransaction.ExtUsed": function () { return $("#extUsed").val(); },
"CallTransaction.StartOfCall": function () { return $("#startOfCall").val(); }
}
See the answer for more details. For understanding: jqGrid uses jQuery.ajax internally and jQuery.ajax uses jQuery.param helper function to process the data parameter (construction using postData) and jQuery.param execute functions if it is the properties of data (postData).
Additionally I would strictly recommend you to use gridview: true option in all your grids (see the answer), add autoencode: true to interpret the input data as the data instead of HTML fragments (it's the default behavior) and to use pager: "#pager" instead of pager: jQuery("#pager").
I recommend you to remove all index properties from colModel and to consider to include additional id property in the data returned from the server with an unique values which come from the database. If some column of the grid already contains the unique value you can add key: true property to the definition of the corresponding column. The reason of such changes is easy to understand if you know that jqGrid have to assign id attribute to every row of grid. The value of id attribute must be unique. The value, used as rowid in the documentation, will be used in the most callbacks of jqGrid to identify the row. The same value will be send to the server if you will implement editing of data later. If you don't specify any rowid in the input data jqGrid have to assign some other value to id. The default value will be 1,2,3... On the other side if you load the data from the database you have native ids of the rows. The usage of the native ids can "simplify your live" in the future.

How do I create a delete button on every row in slickgrid with confirmation?

As the title said it, how do I do it?, I am using this button created by jiri:
How do i create a delete button on every row using the SlickGrid plugin?
when I add an if(confirmation(msg)) inside the function it repeats me the msg ALOT
maybe its because i refresh-ajax the table with each modification.
ask me if you need more info, I am still noob here in stackoverflow :P
(also if there is someway to "kill" the function)
here is the button, iam using(link) i added the idBorrada to check whetever the id was already deleted and dont try to delete it twice, also here is a confirm, but when i touch cancel it asks me again.
$('.del').live('click', function(){
var me = $(this), id = me.attr('id');
//assuming you have used a dataView to create your grid
//also assuming that its variable name is called 'dataView'
//use the following code to get the item to be deleted from it
if(idBorrada != id && confirm("¿Seguro desea eleminarlo?")){
dataView.deleteItem(id);
Wicket.Ajax.ajax({"u":"${url}","c":"${gridId}","ep":{'borrar':JSON.stringify(id, null, 2)}});
//This is possible because in the formatter we have assigned the row id itself as the button id;
//now assuming your grid is called 'grid'
//TODO
grid.invalidate();
idBorrada= id;
}
else{
};
});
and i call the entire function again.
hope that help, sorry for the grammar its not my native language
Follow these steps,
Add a delete link for each row with of the columns object as follows,
var columns =
{ id: "Type", name: "Application Type", field: "ApplicationType", width: 100, cssClass: "cell-title", editor: Slick.Editors.Text, validator: requiredFieldValidator, sortable: true },
{ id: "delete", name: "Action", width: 40, cssClass: "cell-title", formatter: Slick.Formatters.Link }
];
Add a Link Formatter inside slick.formatters.js as follows,
"Formatters": {
"PercentComplete": PercentCompleteFormatter,
"YesNo": YesNoFormatter,
"Link": LinkFormatter
}
function LinkFormatter(row, cell, value, columnDef, dataContext) {
return "<a style='color:#4996D0; text-decoration:none;cursor:pointer' onclick='DeleteData(" + dataContext.Id + ", " + row + ")'>Delete</a>";
}
Add the following delete function in javascript
function DeleteData(id, rowId) {
var result = confirm("Are you sure you want to permenantly delete this record!");
if (result == true) {
if (id) {
$.ajax({
type: "POST",
url: "DeleteURL",
data: { id: id },
dataType: "text",
success: function () {
},
error: function () {
}
});
}
dataView.deleteItem(id);
dataView.refresh();}
}

JQGrid Source not populating after delete

I am using a jqGrid that is set up in the $(document).ready like this:
jQuery("#list").jqGrid({
datatype: 'json',
colNames: ['ID', 'Note', 'Date Added'],
colModel: [
{ name: 'ID', index: 'ID', width: 60, key: true },
{ name: 'ContactNote', index: 'ContactNote', width: 300, cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal;"'; } },
{ name: 'ContactDate', index: 'DateAdded', width: 100 }
],
mtype: 'POST',
viewrecords: true,
jsonReader: { repeatitems: false },
ignoreCase: true,
height: 450,
loadonce: false,
onSelectRow: function (id) { $('#ContactId').val(id); }
});
Here is the HTML of the page:
<div class="col-12">
<div class="ui-content-6 ui-widget-content ui-corner-all">
#using (Html.BeginForm())
{
<h3 class="ui-widget-header ui-corner-all">Enter account number</h3>
<div class="field-container">
#Html.LabelFor(o => o.AccountNumber)
#Html.TextBoxFor(o => o.AccountNumber)
</div>
<div class="form-submit">
<button id="btnSearchContactItems">Get Contact Items</button>
</div>
<h3 class="ui-widget-header ui-corner-all">Contact item list</h3>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div class="form-submit">
<button id="btnRemoveContactItem" type="submit">Remove Selected Contact Item</button>
</div>
#Html.HiddenFor(o => o.ContactId)
#Html.ValidationSummary()
}
</div>
The btnSearchContactItems button has a click event:
$("#btnSearchContactItems").click(function () {
$("#list")
.jqGrid('setGridParam', { postData: { accountNumber: $('#AccountNumber').val() }, url: baseSearchURL })
.trigger('reloadGrid');
return false;
});
Here is the issue:
I am having the user enter in their account number and, on the btnSearchContactItems button click, fill in the grid with some notes. When one of the notes is selected and the btnRemoveContactItem button is clicked the action is called and the note is removed. The problem is that once the not is removed the grid empties. What I would like to happen is to have the grid reload with the data minus the row that was removed.
I swear, for the life of me, I cannot get the data to repopulate. I have tried firing the button click in the grid load, on page load, ect and still nothing. It will only fill the grid again if I physically click the button. Anyone have any thoughts?
How I suppose you don't want to sent any request to the server at the page start. To do this you can use datatype: "local" if you create the grid. You can set url: baseSearchURL at the time of creating of the grid. The parameter will be ignored with datatype: "local".
Now I go back to you main question: you can define postData option directly at the creating of the grid, but you should use functions (methods) as properties (see the answer for details):
postData: {
accountNumber: function () {
var account = $('#AccountNumber').val();
return account ? account : null;
}
}
The method accountNumber will be called every time if grid will be reloaded. So you can use
$("#btnSearchContactItems").click(function () {
$("#list").jqGrid('setGridParam', { datatype: "json" }}).trigger('reloadGrid');
return false;
});
If you want you can additionally set inside of click handler datatype: "local" if $('#AccountNumber').val() is empty.
If you really don't want to send any accountNumber property to the server it the value is null or "" you can use serializeGridData in the following form
serializeGridData: function (postData) {
var propertyName, propertyValue, dataToSend = {}, val;
for (propertyName in postData) {
if (postData.hasOwnProperty(propertyName)) {
propertyValue = postData[propertyName];
val = $.isFunction(propertyValue) ? propertyValue() : propertyValue;
if (propertyName !== "accountNumber" || val) {
// don't send "accountNumber" with empty value
dataToSend[propertyName] = val;
}
}
}
return dataToSend; // ?? probably you can use JSON.stringify(dataToSend);
}
(see the answer for details)
Additionally I would recommend you to set gridview: true to improve performance of the grid and add rowNum: 10000. jqGrid is designed to display paged data. You don't use pager option, but the default value of rowNum is 20. So without setting rowNum: 10000 jqGrid will display only the first 20 rows of data. It's not what you want.

Categories

Resources