Call C# method from another page in javascript function with jQuery - c#

In GridViewData.aspx.cs I have a method I want to call inside a javacsript function.
//This simple example method is from GridViewData.aspx.cs
private int ValidateNameUpdateable()
{
return 22;
}
I want to call this function from Javascript in default.aspx
<script type="text/javascript">
function validateForm()
{
if (ValidateNameUpdateable==22)
{
alert("Name is not updateable, the party already started.");
return false;
}
//if all is good let it update
UpdateInsertData()
}
</script>
Now hears the kicker, I am mostly using jqUery as UpdateInsertData() is a jquery Call and works fine. How do I use ValidateNameUpdateable to call jQuery to return the value from the c# method. . I believe this issue is with my jQuery Call as its just posting and I need to do a $.get or something?
function ValidateNameUpdateable()
{
$(document).ready(function ()
{
$.post("GridViewData.aspx")
});
}

Take a look at this question:
Using jQuery's getJSON method with an ASP.NET Web Form
It shows how to do it.
An example:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
$(function () {
$.ajax({
type: "POST",
url: "WebService.asmx/ValidateNameUpdateable",
data: "{\"input\":5}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// (msg.d is the retrieved data)
var d = msg.d;
if (d == 22) {
alert("OK");
}
else {
alert("Not OK");
}
},
error: function (msg) {
}
});
});
//-->
</script>
</body>
</html>
WebService.cs (in App_Code):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")] // <-- Put something like: services.yourdomain.com in here.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public int ValidateNameUpdateable(int input)
{
return input == 5 ? 22 : -1;
}
}
WebService.asmx:
<%# WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
I hope this explains the idea.
If you want to be able to pass more advanced structures (no int, or string) you might want to consider using JSON.
For the parsing of JSON I'll use the JQuery function parseJSON
All you need to do is create a structure on the web service (struct), and serialize it using the JSON serializer.
Another example using JSON:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
$(function () {
function getRecord(id) {
$.ajax({
type: "POST",
url: "WebService.asmx/GetRecord",
data: "{\"id\":" + id + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// (msg.d is the retrieved data)
var d = $.parseJSON(msg.d);
if (d.RecordExists) {
alert("Record with id: " + d.ID + "\nFirstName: " + d.FirstName + "\nLastName: " + d.LastName);
}
else {
alert("Record doesn't exist.");
}
},
error: function (msg) {
}
});
}
getRecord(1);
getRecord(4);
getRecord(0);
});
//-->
</script>
</body>
</html>
WebService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
/// <summary>
/// Summary description for WebService
/// </summary>
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")] // <-- Put something like: services.yourdomain.com in here.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {
[Serializable]
protected class Record
{
public bool RecordExists { get; set; }
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Record() // Initializes default values
{
RecordExists = true;
ID = 0;
FirstName = "";
LastName = "";
}
}
[WebMethod]
public string GetRecord(int id)
{
// Initialize the result
Record resultRecord = new Record();
resultRecord.RecordExists = true;
resultRecord.ID = id;
// Query database to get record...
switch (id)
{
case 0:
resultRecord.FirstName = "John";
resultRecord.LastName = "Something";
break;
case 1:
resultRecord.FirstName = "Foo";
resultRecord.LastName = "Foo2";
break;
default:
resultRecord.RecordExists = false;
break;
}
// Serialize the result here, and return it to JavaScript.
// The JavaScriptSerializer serializes to JSON.
return new JavaScriptSerializer().Serialize(resultRecord);
}
}
Please note that AJAX is Asynchronous, that means that even tough the pages are requested in a specific order, they are not received in a specific order. That means that even tough you request the records in order: 1, 4, 0, they can be received in any order, like 4, 1, 0, or 1, 0, 4.

I think you are looking for ajax. It lets you make asynchronous calls to a server and get the restult. You should make a simple aspx page that takes some request arguments and outputs the correct information. Then use ajax to call load that page and get the results.
here is a basic overview of ajax
http://www.prototypejs.org/learn/introduction-to-ajax
Here is the jQuery ajax call
http://api.jquery.com/jQuery.ajax/

Maybe your solution is to use load():
http://api.jquery.com/load/

You can't do it directly, you need to post your data through an httphandler (ashx), for example. Then your handler returns a json object. You delve into to find the response you want.
ASP.NET - Passing JSON from jQuery to ASHX
[]'s

Related

ASP.Net C# Google Charts not displaying when running

I'm working on an ASP.Net C# Google Charts internal reporting site but am having trouble getting the chart to display. Code seems to run fine and allows me to run in debug.
I can get to the ASP page, but there is no chart present.
EDIT: Initial issue was down to misplaced ], how silly of me!
I'm now faced with the following in the Browser Console, can any help?
A Parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message.See
https://www.chromestatus.com/feature/5718547946799104 for more details
.
Code below;
ASP Page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master"
AutoEventWireup="true" CodeBehind="ADMReports.aspx.cs"
Inherits="ADMReports.ADMReports" %>
<%# Register Assembly="ADMReports" Namespace="ADMReports" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<div id="b_sale" style="width:500px; height:300px;">
TEST
</div>
</body>
<script>
// VISUALIZATION API.
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(createPIE);
function createPIE() {
// SET CHART OPTIONS.
var options = {
title: 'Total Invoices Per Month',
colors: ['#888', 'orange'],
is3D: true
};
$.ajax({
url: "ADMReports.aspx",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrValues = [['Year', 'Month', 'OrdersProcessed']]; // DEFINE AN ARRAY.
var iCnt = 0;
$.each(data.d, function () {
// POPULATE ARRAY WITH THE EXTRACTED DATA.
arrValues.push([data.d[iCnt].Year, data.d[iCnt].Month], data.d[iCnt].OrdersProcessed]);
iCnt += 1;
});
var figures = google.visualization.arrayToDataTable(arrValues)
var chart = new google.visualization.PieChart(document.getElementById('b_sale'));
chart.draw(figures, options);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
</script>
</html>
Code behind asp page
I will be amending the SQL query to pull from a Stored Procedure, but kept it simple for testing purposes.
public partial class ADMReports : System.Web.UI.Page
{
private string Year;
private string Month;
private int OrdersProcessed;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public List<ADMReports> Total_Invoices()
{
List<ADMReports> Invoices = new List<ADMReports>();
string sConnString = "Data Source=<servername>;Initial Catalog=<DB>;Integrated Security=True";
SqlConnection myConn = new SqlConnection(sConnString);
SqlCommand objComm = new SqlCommand("SELECT YEAR(DateTimeScanned) AS Year, MONTH(DateTimeScanned) AS Month, COUNT(OrderNumber) AS OrdersProcessed FROM tabTrace WHERE YEAR(DateTimeScanned) = YEAR(GETDATE()) GROUP BY MONTH(DateTimeScanned), YEAR(DateTimeScanned) ORDER BY MONTH ASC ", myConn);
myConn.Open();
SqlDataReader sdr = objComm.ExecuteReader();
while (sdr.Read())
{
ADMReports objValues = new ADMReports();
objValues.Year = sdr["Year"].ToString();
objValues.Month = sdr["Month"].ToString();
objValues.OrdersProcessed = (int)sdr["OrdersProcessed"];
Invoices.Add(objValues);
}
myConn.Close();
sdr.Close();
return Invoices;
}
}
I would strongly recommend to add all related scripts in local project and remove links to third-party references eg. google in this case. This will help in reducing load time for page also you will not be surprised with random updates of such scripts which are hosted on other server.

ASP.Net WebAPI 500 (Internal Server Error)

I have followed the tutorial located here:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
However, the main difference is I am using a 3rd party library to get a list of objects which I would like to return to the client.
Here is my index.html file:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Routes</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
</head>
<body>
<div>
<h2>All Routes</h2>
<ul id="routes" />
</div>
<script>
var uri = '../api/MH_Route_Selection';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#routes'));
});
});
});
</script>
</body>
</html>
My controller file:
namespace LMVeKanban.Controllers
{
public class MH_Route_SelectionController : ApiController
{
//GET ROUTES METHOD FOR URI: /api/MH_Route_Selection
[HttpGet]
public IHttpActionResult GetRouteList()
{
var routeManager = new LmvRouteManager(1);
List<Route> routes = routeManager.GetRoutes();
return Ok(Json(routes));
}
}
Everything works fine, the controller gets called and the return value routes, looks like: http://imageshack.com/a/img661/5648/ZQ59Rt.jpg
After the controller passes the list back, I get a 500 error from the server with no clue where it went wrong.
EDIT: Watching the Ok(routes) value shows that it has successfully converted the object:
EDIT 2: I have tried the following which also returns a 500 error in the same manner as the previous attempt
public HttpResponseMessage GetRouteList()
{
var routeManager = new LmvRouteManager(1);
List<Route> routes = routeManager.GetRoutes();
return Request.CreateResponse(HttpStatusCode.OK, routes);
}

Deserialize a string in a generic List<> explodes with double quotes

When attempting to retrieve and store a serialized list of data in local storage then subsequently sending to back to the server to be deserialized to it's original form, the process explodes when a string in the object contains an escaped double quote.
If the object is NOT in a collection (I've tried a List and ArrayObject), the code works fine. What is it about a collection that causes grief?
Can someone please tell me what I'm doing wrong here, or suggest a better method to achieve the same result. I came across this problem while trying to create an offline web application.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="_default" %>
<!DOCTYPE html>
<html lang="en">
<body>
<form runat="server">
<div id="Feedback"></div>
<div>Export</div>
<div>Import</div>
</form>
<script src="js/jquery-2.1.1.min.js"></script>
<script>
function Export() {
$.ajax({
type: "POST",
url: 'default.aspx/GetThings',
contentType: "application/json; charset=u",
dataType: "json",
async: true,
success: function (result) {
var json = result.d;
$('#Feedback').html(json);
// failed attempt #1
//localStorage["things"] = json;
// failed attempt #2
var things = jQuery.parseJSON(json);
localStorage["things"] = JSON.stringify(things);
}
});
}
function Import() {
$.ajax({
type: "POST",
url: "default.aspx/PutThings",
data: "{'json':'" + localStorage["things"] + "'}",
contentType: "application/json; charset=u",
dataType: "json",
async: true,
success: function (result) {
$('#Feedback').html(result.d);
}
});
}
$(function () {
$("#ExportButton").click(function () {
Export();
});
$("#ImportButton").click(function () {
Import();
});
});
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
public partial class _default : Page
{
[WebMethod]
public static string GetThings()
{
List<Thing> things = new List<Thing>();
Thing thing = new Thing();
//thing.Description = "no escaped double quote string works fine";
thing.Description = "100 (2 1/8\") Gear";
things.Add(thing);
JavaScriptSerializer serializer = new JavaScriptSerializer();
StringBuilder json = new StringBuilder();
serializer.Serialize(things, json);
return json.ToString();
}
[WebMethod]
public static string PutThings(string json)
{
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Thing> things = serializer.Deserialize<List<Thing>>(json);
return things[0].Description;
}
catch (Exception e)
{
return e.Message;
}
}
public class Thing
{
[DataMember]
public string Description { get; set; }
}
}
Put a breakpoint in the top of the PutThings() method, hope you have a good reason to serialise/deserialise manually rather then just letting WCF take care of this for you.
When you've got the breakpoint you can take a look at the JSON string passed to the service and you'll be able to tell for yourself what kind of transform is needed to make it into a valid JSON string. I would guess that it's the build of the data string being sent to this function, as it looks like your placing quotes around the child JSON object string localStorage["things"]. The code should read..
data: "{'json':" + localStorage["things"] + "}",
If not, please post the JSON string being passed to your Put function and I'll be able to give you a more accurate answer.

Retrieve value from webservice called from javascript?

Is it possible to retrieve value or date from calling a webmethode from javascript, here is a sample code:
//This method is in a webservice.asmx file.
[WebMethod]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{
return Cities.GetAllCitiesByCountry(CountryID: countryID);
}
<script language="javascript" type="text/javascript">
function fillCities() {
var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>');
var selectedIndex = dropDownList.selectedIndex;
var value = dropDownList[selectedIndex].value;
WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, "");
}
function onSuccess(result){
alert(result[0].(PropertyName));
}
The variable x doesn't retrieve anything and I guess that it produce an error. I have tried to define an array but still it didn't work. Any idea ?
Edit:
The above code have been altered and is now an answer to my question along with the answer below which used JQuery.
Use Json response with Jquery, Its realy cool and easy.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class CitiService : WebService
{
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{
List<tbl_City> cities = GetCities(countryID);
JavaScriptSerializer js = new JavaScriptSerializer();
var jsonObj = js.Serialize(cities);
Context.Response.Clear();
Context.Response.Write(jsonObj);
Context.Response.End();
}
}
on ASp.net page
<script language="javascript" type="text/javascript">
$.ajax({
url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>',
dataType: "json",
data: "{countryID:'100'}",
success: function (result) {
alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid
}
});
you can do this easily with JQuery and ASP.NET webmethods Encosia
You need to register your web service with ScriptManager and then call it from the client side. Take a look on this tutorial:
Client-Side Web Service Calls with AJAX Extensions
Also you can use web service with jQuery but in this case you need to switch to JSON: Calling ASMX from jQuery

getting jQuery Ajax return data in Asp.Net

I'm a newbie in jQuery and don't understand how in jQuery Ajax returns data. I have some simple function to get some data like below
[WebMethod(EnableSession = false)]
protected int SignIn()
{
return 0;
}
and in my .aspx page I have this
$(document).ready(function () {
$("#si").click(function
() {
$.ajax({
type: "POST",
url: "SignIn.aspx/SignIn",
contentType: "application/json",
success: function (txt) {
alert(txt);
}
});
});
});
but in alert I get the whole SignIn.aspx (all html tags and so on). how to alert the 0 which the SignIn() returns?thanks
Make the SignIn method static and public and show alert with following code: alert(txt.d);
You are asking an ASPX file for data and I think that should be an ASMX.
Check out Dave Ward's post where I leaned about all this: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
The simplest example I could make looks like this:
Add a Web Service (ASMX) containing
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public int Status(int input) {
return input + 1;
}
}
Then in your HTML do
<html>
<head>
<title>Test</title>
<script src="jquery-1.6.2.min.js" ></script>
</head>
<body>
<script>
$(function () {
$.ajax({
url: 'WebService.asmx/Status',
data: '{ input: 0 }',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (data, status) {
alert(data);
alert(typeof data);
}
});
});
</script>
</body>
</html>
In the ajax call the string defined in data is the input to the web method. Names must match. In the success callback, the first alert shows the value returned (input plus one) and the second alert shows that it is a number, not a string. Because the datatype is set to JSON, the web method returns JSON allowing the data to be typed correctly.
Hope this helps.
Try this sample. I have passed the id from aspx to handler and just returned from there to show the server side data to aspx again
this is sample example .....
Handler code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProject
{
/// <summary>
/// Summary description for TestHandler1
/// </summary>
public class TestHandler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string id = context.Request["id"];
context.Response.ContentType = "text/plain";
context.Response.Write(id);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
and in aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
</form>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: 'TestHandler.ashx?id='+ 1,
data: 'id=' + 1,
success: function (msg) {
alert(msg);
}
});
});
</script>
</body>
</html>

Categories

Resources