asp.net ScriptManager PageMethods is undefined - javascript

I want to call static server-side methods from JS so i decide to use ScriptManager control on my site.
So i have a master page, with such structure:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="TopLevelMasterPage.Master.cs"
Inherits="Likedrive.MasterPages.TopLevelMasterPage" %>
<!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"
xmlns:fb="http://ogp.me/ns/fb#">
<head runat="server">
<title></title>
<script type="text/javascript">
function getGiftFileUrl() {
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
PageMethods.GetGiftFileUrl("hero", 1024, 768, OnSuccess, OnError);
}
getGiftFileUrl();
</script>
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManagerMain"
runat="server"
EnablePageMethods="true"
ScriptMode="Release"
LoadScriptsBeforeUI="true">
</asp:ScriptManager>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
</html>
But when page is loading, i have a JS exception - PageMethods is undefined.
I supposed that object will be created implicit so i can use it in my javascript.

To use PageMethods you need to follow these steps:
You need to use ScriptManager and set EnablePageMethods. (You did).
Create a static method in your code behind and use the [WebMethod] attribute.
Call you method in javascript like you should do in C# but you have more parameter do fill, the sucess and error callbacks. (You did).
Did you miss any of these steps?
Edit:
Just realized you did this:
function getGiftFileUrl() {
function OnSuccess...
You have yours callbacks inside a function. You need yours callbacks like this:
function OnSuccess(response) {
alert(response);
}
function OnError(error) {
alert(error);
}
PageMethods.GetGiftFileUrl("hero", 1024, 768, OnSuccess, OnError);
And you code behind probably will end in something like that:
[WebMethod]
public static string GetGiftFileUrl(string name, int width, int height)
{
//... work
return "the url you expected";
}
Bonus: Since it is a static method you can't use this.Session["mySessionKey"], but you can do HttpContext.Current.Session["mySessionKey"].

In your codebehind create this method:
[WebMethod]
public static void GetGiftFileUrl(string value1, int value2, int value3)
{
// Do Stuff
}
your js script should resemble this too:
<script type="text/javascript">
function getGiftFileUrl() {
PageMethods.GetGiftFileUrl("hero", 1024, 768, OnSucceeded, OnFailed);
}
function OnSucceeded(response) {
alert(response);
}
function OnFailed(error) {
alert(error);
}
getGiftFileUrl();
</script>

I've realize why the PageMethod object was undefinded, because ScriptManager component placed next from the script that uses PageMethod, so when page is rendered and script executed, there is no PageMethod at this moment. So i need to call getGiftFileUrl() on button click or on window load event, when all scripts on page are ready to use.

<script type="text/javascript">
function Generate()
{
var result = PageMethods.GenerateOTP(your parameter, function (response)
{
alert(response);
});
}
</script>
Will 100% work.

Related

Google OAuth2 Callback empty

I am attempting THIS OFFICIAL GOOGLE EXAMPLE and am running into an empty object/array on the sign in callback. The ONLY modifications I have made to this from Google's examples are the console.logs the alerts and a small syntax error they had
I changed
auth2.grantOfflineAccess().then(signInCallback);
to
auth2.grantOfflineAccess().then(signInCallback());
Without the () the function wouldn't fire. and the made that alert would not display. Now having copied this DIRECTLY from Google's page, have I missed something or is there another bug that I missed?
Also worth noting -- The origins are set up:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html itemscope itemtype="http://schema.org/Article">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
client_id: 'xxxxxxxx.apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/plus.business.manage'
});
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function () {
// signInCallback defined in step 6.
alert('made this');
let test = auth2.grantOfflineAccess().then(signInCallback());
console.log(test);
});
function signInCallback(authResult) {
alert('made that');
console.log(authResult);
if (authResult['code']) {
// Send the code to the server
} else {
// There was an error.
}
}
</script>
</body>
</html>
My console.log(authResult); just inside the signInCallback() function is empty -> undefined. I am able to get my user logged in and the pop-up indicates all scopes are granted. Why am I not able to grab the access token?

Calling C# public void function inside a javascript keypress

I've been searching for a longtime, How can I call my public void search() inside my javascript keypress. Newb in asp.net Thanks!
This is my aspx code.
<script language="javascript" type="text/javascript">
window.addEventListener("keyup", checkKeypress, false);
function checkKeypress(key) {
var TestVar = document.getElementById('<%= Search_Employee.ClientID %>');
'<% search(); %>';
}
</script>
[System.Web.Services.WebMethod]
public static void GetData()
{
MessageBox.Show("Calling From Client Side");
//Your Logic comes here
}
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"/>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function CallingServerSideFunction() {
PageMethods.GetData();
}
</script>
</form>
</body>

Javascript: Call C# codebehind string function but return all HTML of current page

I am using PageMethods to call C# function from Javascript.
My C# function is return as String.
But after i called that function from Javascript it returned current page.
Here my code:
ASPX:
<form id="form1" runat="server" method="post">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script>
function testPageMethods(){
var id = 45;
PageMethods.returnStr4Frontend(id, onSucess, onError);
}
function onSucess(result) {
console.log(result);
}
function onError(result) {
console.log(has error);
}
testPageMethods();
</script>
</form>
ASPX.CS
[WebMethod]
public static string returnStr4Frontend(string id)
{
string reStr = string.Empty;
reStr = "Your id is: " + id;
return reStr;
}
When i run my page on browser, i received wrong result was (all html code of current page):
<form id="form1" runat="server" method="post">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script>
function testPageMethods(){
var id = 45;
PageMethods.returnStr4Frontend(id, onSucess, onError);
}
function onSucess(result) {
console.log(result);
}
function onError(result) {
console.log(has error);
}
testPageMethods();
</script>
</form>
Check this nugget
https://www.nuget.org/packages/HtmlAgilityPack
it will get the html code depending on the domain you entered

Open a popup containing ASPX postback result

I have an ASPX page with many fields that generate PDF documents when I click an "export to PDF" button.
I'd now like to have a "print PDF" button in JavaScript that does something like this:
w = window.open(?);
w.print();
w.close();
where "?" will perform the same postback as my "export to PDF" button.
If you need to submit (postback) your form to new window you can try to change form target to fake, like:
var form = $("form");
form.attr("target", "__foo");
Submit a form.
form.submit();
And remove the target (setitmeout(,1) - pot the event in end of js "event-queue", in our case - after form submitting):
setTimeout(function () { form.removeAttr("target"); }, 1);
Also, before submit you can try to open window with __foo id for more styling, and the form will submitted (postback) in this window instead of a new one:
var wnd = window.open('', '__foo', 'width=450,height=300,status=yes,resizable=yes,scrollbars=yes');
But I have no idea how to handle the submitted window and catch the onload or jquery's ready event. If you can do it share the workaround please and call the wnd.print(); You can play with iframes inside this wnd and maybe you will find a solution.
Updated:
Try to have a look in this prototype [tested in Chrome]:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
function PrintResult() {
var wnd, checker, debug;
debug = true;
// create popup window
wnd = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');
// create "watermark" __loading.
wnd.document.write("<h1 id='__loading'>Loading...</h1>");
// submit form to popup window
$("form").attr("target", "__foo");
setTimeout(function() { $("form").removeAttr("target"); }, 1);
if (debug)
{
$("#log").remove();
$("body").append($("<div id='log'/>"));
}
// check for watermark
checker =
setInterval(function () {
if (debug) $("#log").append('. ');
try {
if (wnd.closed) { clearInterval(checker); return; }
// if watermark is gone
if (wnd.document == undefined || wnd.document.getElementById("__loading") == undefined) {
if (debug) $("#log").append(' printing.');
//stop checker
clearInterval(checker);
// print the document
setTimeout(function() {
wnd.print();
wnd.close();
}, 100);
}
} catch (e) {
// ooops...
clearInterval(checker);
if (debug) $("#log").append(e);
}
}, 10);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="ReportButton" OnClick="ReportRenderClick" Text="Export to PDF" OnClientClick="PrintResult()"/>
<asp:Button runat="server" Text="Just a button."/>
</div>
</form>
</body>
</html>
And here is .cs file:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ReportRenderClick(object sender, EventArgs e)
{
Response.Clear();
Thread.Sleep(2000);
Response.ContentType = "application/pdf";
Response.WriteFile("d:\\1.pdf");
//Response.ContentType = "image/jpeg";
//Response.WriteFile("d:\\1.jpg");
//Response.Write("Hello!");
Response.End();
}
}
Open the pdf window with IFrame and you could do this:
Parent Frame content
<script>
window.onload=function() {
window.frames["pdf"].focus();
window.frames["pdf"].print();
}
</script>
<iframe name="pdf" src="url/to/pdf/generation"></iframe>
Inspired from this https://stackoverflow.com/a/9616706
In your question tag you have the asp.net tag, so I guess you have access to some kind of ASP.NET server technology.
I would suggest to do it like this:
Create a HttpHandler or an ASP.NET MVC action that returns a FileContentResult
In your page, use this code to download and print the file (actually found it here, pasting it for future reference!)
Click here to download the printable version
There are some good tutorials on writing the server side:
Walkthrough: Creating a Synchronous HTTP Handler
How to get particular image from the database?
And one of my own: Download PDF file from Web location and Prompt user SaveAs box on client in web-Application ASP C#

Easy openid? .NET/JS?

I tried to understand dotnetopenid and failed. I dont know asp.net well enough and i want to do this problematically.
Is there a simple JS openid lib? or a simple/good openid example doing it for a C# desktop application?
Here is an example of open ID in c# .net . Not desktop but web.
http://www.nikhedonia.com/notebook/entry/openid-and-asp-net-mvc/
Here is my aspx file, i only added one line, the WebApplication1.openidtest.Authenticate line
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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>
<form id="form1" runat="server">
<div>
<% WebApplication1.openidtest.Authenticate("http://your_id.myopenid.com/"); %>
</div>
</form>
</body>
</html>
Here is the cs file. Note it works but doesnt handle things like errors and really is just for testing/breakpoints.
NOTE: If email is required and the user submit a persona that doesnt have an email there will be no email listed thus you must check and handle accordingly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetOpenAuth;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
namespace WebApplication1
{
static public class openidtest
{
static public void Authenticate(string openIdIdentifier)
{
var openId = new OpenIdRelyingParty();
var response = openId.GetResponse();
if (UserNeedsToLogin(response))
{
var request = openId.CreateRequest(openIdIdentifier);
request.AddExtension(new ClaimsRequest { Email = DemandLevel.Require });
request.RedirectingResponse.Send();
return;
}
HandleAuthenticationResponse(response);
}
static bool UserNeedsToLogin(IAuthenticationResponse response)
{
return response == null;
}
static void HandleAuthenticationResponse(IAuthenticationResponse response)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
{
var claims = response.GetExtension<ClaimsResponse>();
if (claims != null)
{
var s = claims.Email;
}
return;
//return HandleSuccessfulLogin(response);
}
case AuthenticationStatus.Canceled:
//_context.ErrorMessage = "Login was cancelled at the provider.";
break;
case AuthenticationStatus.Failed:
//_context.ErrorMessage = "Login failed at the provider.";
break;
case AuthenticationStatus.SetupRequired:
//_context.ErrorMessage = "The provider requires setup.";
break;
default:
//_context.ErrorMessage = "Login failed.";
break;
}
}
}
}

Categories

Resources