try catch on static function asp.net - javascript

i try show error message
i have a link button in grid view ..i call highcharts when i click on this link button and also this static function.. through this static function i get data and then call this function through javascript so when i click on this button chart is display but when there is no chart it shows error in code so for this i want to show alert box when there is no chart..
public static function(int ID)
try
{
}
catch (Exception ex)
{
Response.Write("<script>alert('" + Server.HtmlEncode(ex.ToString()) + "')</script>");
}
i try above but this shows error message
Error 3 An object reference is required for the non-static field,
method, or property 'System.Web.UI.Page.Server.get'
Error 2 An object
reference is required for the non-static field, method, or property
'System.Web.UI.Page.Response.get'
lbViewChart is link button ...
jquery
<script type="text/javascript">
var strArray = "[['sfdsdfLi', 9],['Kiwsdfi', 3],['Mixesdfd nuts', 1],['Oranges', 6],['Grapes (bunch)', 1]]";
$(function () {
$('[ID*=lbViewChart]').on('click', function () {
var row = $(this).closest('tr');
var Id = row.find('td')[0].firstChild.data;
var obj = {};
obj.ID = Id;
GetData(obj);
return false;
});
});
function GetData(obj) {
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetVoiliations",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert(result.d);
alert('u');
//start
strArray = result.d;
var myarray = eval(strArray);
$('#container').highcharts({
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Contents of Highsoft\'s weekly fruit delivery'
},
subtitle: {
text: '3D donut in Highcharts'
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45
}
},
series: [{
name: 'Delivered amount',
data: myarray
}]
});
//end
},
error: function (error) {
alert(error);
}
});
}
// });
</script>
any solution?

You cannot access Server directly in a static method instead for that use System.Web.HttpContext.Current.Server So the code will be like:
System.Web.HttpContext.Current.Response.Write("<script>alert('" + System.Web.HttpContext.Current.Server.HtmlEncode(ex.ToString()) + "')</script>");
Or include using System.Web; to the using section and then use HttpContext.Current.Server
Updates: -
The HttpContext.Current is a static property so you can access it Directly inside a static method. and hence you can access .Server and .Response` from this as like the following:
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
currentContext.Response.Write("<script>alert('" + currentContext.Server.HtmlEncode(ex.ToString()) + "')</script>");

Related

How can i refere to an object variable dynamically?

Im creating multiple charts at the same page, now i want a smart function to either update a single chart or all of them
It works fine when i hard code the object name but i want to be able to get the object name from the button it was executed from
<button class="update" name="prodChart1" funtionName="f_A_GetTotalWorkedHours"> Test</button>
var prodChart1 = document.getElementById('ProdChart1');
var prodChart1 = new Chart( prodChart1, {
type: "line",
data: <%=f_A_GetTotalWorkedHours(Dateadd("d",-2,Date), Date, 48, Line, "")%>,
options: {
color: 'red',
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
$(".update").click(function(){
UpdateChart($(this).attr("name"),"")
});
function UpdateChart(chartName, aFunction) {
$.ajax({
type: 'POST', //post method
url: 'AnalyticsAPI.asp?',
dataType: "text",
data: {requestParam: 'f_A_GetTotalWorkedHours|'+ getParam()[0] +'|'+ getParam()[1] +'|48' },
success: function (result, textStatus, jqXHR)
{
data3= result;
chartName.config.data = JSON.parse(data3);
chartName.update();
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.status);
alert(thrownError);
}
});
};
So the "update" function should get the name of the existing chart object, the object name is part of the button name attribute.
The error i get is that "UpdateChart(chartName, aFunction)" chartname isnt a object. If i would hardcode the object name in the call it works.
Try this: Get global variable dynamically by name string in JavaScript
Or add your chart to an Object of which you can access the keys:
var charts = {};
charts.populationIncrease = new Chart(...);
function updateChart(chartName, value) {
charts[chartName].value = value;
}
updateChart('populationIncrease', { ... });
Issue you have is that you are trying to access the objects property (getting and setting) however you are trying to access properties of the string $(this).attr("name")
where instead you should be using $(this)
see fixed code below
var prodChart1 = document.getElementById('ProdChart1');
var prodChart1 = new Chart( prodChart1, {
type: "line",
data: <%=f_A_GetTotalWorkedHours(Dateadd("d",-2,Date), Date, 48, Line, "")%>,
options: {
color: 'red',
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
$(".update").click(function(){
UpdateChart($(this), $(this).attr("name"),""); //Pass in the object and the name
});
function UpdateChart(chartObject, chartName, aFunction) {
$.ajax({
type: 'POST', //post method
url: 'AnalyticsAPI.asp?',
dataType: "text",
data: {requestParam: 'f_A_GetTotalWorkedHours|'+ getParam()[0] +'|'+ getParam()[1] +'|48' },
success: function (result, textStatus, jqXHR)
{
data3= result;
chartObject.config.data = JSON.parse(data3); //you are using the object not the string attribute of name
chartObject.update();
},
error: function (xhr, ajaxOptions, thrownError) {
// alert(xhr.status);
alert(thrownError);
}
});
};

Redrawing the highchart column type graph on ajax success function

Actually i want to redraw the HighChart Bargraph on Ajax Success Function in which the parameter is send need help.
Below are my code
On Page Load Code (It Runs Perfect)
<script>
var chart = $(function () {
$('#chart').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Overdue Projects'
},
xAxis: {
categories: <?php print_r(isset($project) ? $project : []); ?>
},
yAxis: {
title: {
text: 'Hours'
}
},
series: <?php print_r($series); ?>
}, function (chart) { // on complete
if (chart.series.length < 1) { // check series is empty
console.log('Data Empty');
chart.renderer.text('No Data Available', 380, 120)
.css({
color: '#4572A7',
fontSize: '16px'
})
.add();
}
});
});
</script>
On Ajax Success Function Code (Unable to Update the series and categories)
<script>
$("select[name=GraphPro]").on('change', function () {
var proId = $(this).val();
$.ajax({
data: 'proId=' + proId,
type: "post",
url: "<?php echo base_url('admin_dashboard/drawBarChart'); ?>",
dataType: "json",
success: function (xyz)
{
var project = xyz.project;
chart.series = xyz.series;
var chart1 = new Highcharts.Chart(chart);
}
})
})
</script>
Really hard to say for sure without seeing the data in your variables what you are aiming for with the project variable.
That said, to update the chart (read: change) you can do the following assuming chart is the variable of your already existing chart;
Updated as per your comment:
<script>
$("select[name=GraphPro]").on('change', function () {
var proId = $(this).val();
$.ajax({
data: 'proId=' + proId,
type: "post",
url: "<?php echo base_url('admin_dashboard/drawBarChart'); ?>",
dataType: "json",
success:function(xyz) {
console.log(xyz.project); //Value is ["Chat"]
console.log(xyz.series); // Value is [{"name":"Estimated Hours","data":[3]},{"name":"Consumed Hours","data":[12]}]
chart.update({
xAxis:{ categories: xyz.project //print as xyz.project instead of above project value
},
series: xyz.series // print as xyz.series instead of above series value
});
}
})
})
</script>
Highchart API on update: http://api.highcharts.com/class-reference/Highcharts.Chart#update
Working example using update when button is clicked: http://jsfiddle.net/ewolden/crhh39v6/
To add additional series to your chart you need to use addSeries, like this:
<script>
$("select[name=GraphPro]").on('change', function () {
var proId = $(this).val();
$.ajax({
data: 'proId=' + proId,
type: "post",
url: "<?php echo base_url('admin_dashboard/drawBarChart'); ?>",
dataType: "json",
success: function (xyz)
{
var project = xyz.project; //don't know what the plan with this variable is
chart.addSeries(xyz.series);
}
})
})
</script>
Highchart API on addChart: http://api.highcharts.com/class-reference/Highcharts.Chart#addSeries

Unable to load the dropdown list on a kendo window from a method using Webservice

On clicking Edit button on a Page a method is triggered and a window which uses a kendo template is opened . One of the control on the kendo window is Kendo dropdown list which needs to have values comming from the webmethod.The error i am getting on clicking of the edit button is 'Object doesn't support property or method 'slice'. Below is my code for the Edit button.
function edit(item) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node}))
.appendTo("body")
.kendoWindow({
modal: true,
activate:function(){
$("#roles").kendoDropDownList({
dataTextField: "Countryname",
dataValueField: "CountryId",
dataSource: {
transport: {
read: {
url: "/Services/MenuServices.asmx/getcountries",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
}
}
}
})
},
deactivate: function () {
this.destroy();
}
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var Id = $('#ID').val();
node.set("id", Id);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("id", Id);
treenode.ID = Id;
console.log(JSON.stringify(treenode));
})
}
IS there any property for Kendo window that triggers this service when its opened.Right now i am using activate event but its not working.tried using 'Open' event also.
Thanks
I added the Schema part to the datasource and it worked.
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: { // define the model of the data source. Required for validation and property types.
id: "CountryId",
fields: {
CountryId: { editable: false, nullable: false, type: "string" },
Countryname: { editable: true, nullable: true, type: "string" },
}
},
},

Data not populating the table created using jsgrid

I'm using jsgrid to create an editable table. i used the code from this demo. The only difference is im using mvc instead of web api.
Looking at the network, the controller returns the needed json data and jsgrid also shows the pagination stuff on the bottom of the table. However, the table is not being populated
Here's the html and javascript code
<div id="jsGrid"></div>
#section scripts {
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script>
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "get",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
},
updateItem: function (item) {
},
deleteItem: function (item) {
}
},
fields: [
{ name: "SKU", type: "text", width: 50 },
{ name: "PartNumber", type: "text", width: 100 },
{ name: "ProductLineName", type: "text", width: 50 },
{ name: "ProductLineId", type: "text", width: 50 },
{ name: "Deleted", type: "checkbox", sorting: false },
{ type: "control" }
]
});
</script>
Here's the relevant method in the controller
public async Task<ActionResult> Get()
{
var query = db.Products
.Select(p => new ProductDto()
{
PartNumber = p.PartNumber,
SKU = p.SKU,
ProductLineName = p.ProductLines.ProductLineName,
ProductLineId = p.ProductLineId,
Deleted = p.Deleted
});
var products = await query.ToListAsync();
return Json(products, JsonRequestBehavior.AllowGet);
}
Anyone know what i can do to display/bind the returned data to the table?
Change your loadData call because its not specifying what to do when ajax call is done.
Try to rewrite it like below :
controller: {
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "get",
dataType: "json",
data: filter
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
},
This is the client side javascript that I used which finally put some data in the grid: (just the controller part)
controller: {
loadData: function (filter) {
console.log("1. loadData");
return $.ajax({
type: "GET",
url: "/Timesheet/GetTimesheet/",
dataType: "json",
data: filter
console.log("3. loadData complete");
}
None of the posted explicit promise code functioned at all. Apparently $.ajax returns a promise.
and this was my MVC controller code that I called with ajax (C#):
public async Task<ActionResult> GetTimesheet()
{
int id = Convert.ToInt32(Session["UID"]);
var tl = (
from ts in db.Tasks
orderby ts.Task_Date descending
where ts.Emp_ID == id
select new
{
ID = ts.Task_ID,
Date = ts.Task_Date,
Client = ts.Customer_ID,
Hours = ts.Total_Hours
}
).Take(4);
var jsonData = await tl.ToListAsync();
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
There are no actual examples of required Json for jsGrid. anywhere but this worked for me - note no headers or anything.

Load data to highchart using ajax

I'm loading a highchart graph using following function.
function reloadSubGraph(data){
$(function () {
$('#SubPatternContainer').highcharts({
plotOptions: {
events: {
update: function (event) {
}
}
},
title: {
text: 'Selected Pattern'
},
series:[{data:[[1,200],[2,200],[3,200]]}]
});
});
}
It works fine, but when using ajax call to load data as follows for same data string [{data:[[1,200],[2,200],[3,200]]}] as follows it doesn't show on graph.
function getSubPatternData(patternId,patternName){
$.ajax({
url: "/arcane/patternData1?patternId="+patternId+"&patternName="+patternName,
type: "get",
cache: false,
success: function(data) {
var tempdata=String(data);
reloadSubGraph(tempdata);
},
error:function(xhr, status, error){
alert(xhr.responseText);
}
});
}
Can anyone point me where i'm doing wrong here. when I see the returned results of ajax using alert(data) it shows the same string that i used in reloadSubGraph() function ([{data:[[1,200],[2,200],[3,200]]}])
when using with ajax i changed reloadSubGraph() funcion as follows.
function reloadSubGraph(data){
alert(data);
$(function () {<!--from w w w .j ava 2 s . c o m-->
$('#SubPatternContainer').highcharts({
plotOptions: {
events: {
update: function (event) {
}
}
},
title: {
text: 'Selected Pattern'
},
series:data
});
});
}

Categories

Resources