Can't Use PageMethod (ajax in C# .net) - c#

I try to use PageMethod in asp.net.
First I add script Manager to my aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
I wrote onClick method on JS:
function TryAJAX() {
PageMethods.TryA( onSucess, onError);
function onSucess(result) {
alert('good.');
}
function onError(result) {
alert('Something wrong.');
}
}
and in the code behind:
[WebMethod]
public static String TryA()
{
return "JSON CHECK";
}
and I always get the message 'something wrong' . althouth that in debugger I see it's enter to the methood 'TryA'.
What is the problem?
thanks!!

i know this is not the exact path you were looking to take for a solution, but I think it is a WAY better option, so here's my 2 cents...
your button in html
<input type="button" id="myStupidButton" value="Click Me Yo" />
you javascript- I am going to use jQuery too , if that is really a problem I can give you a pure js option:
<script>
$(function(){
$(document).on('click', '#myStupidButton', function(){
$.ajax({
type: "POST",
url: "Mypage.aspx/TryA",
success: function(data){
// parse asp.net's response
data = $.parseJson(data);
//asp.net wraps all json into json like this "d" : "yourresponse"
alert(data.d);
}
});
});

Related

Calling to c# function from javascript function

I have a javascript function and c# fanction. I need to call to the c# function from the javascript function, but I don't know how...
Can someone help me?
Thank you!
The javascript function-
<script type="text/javascript" language="javascript">
function DeleteBook(idimg) {
// idimg is a string
var userConfirm = window.confirm('Are you sure?');
if (userConfirm == true) {
control.Sess(idimg);// The line which is colling to the c# function - doesn't work
window.open('Delete.aspx');
}
else
return false;
}
</script>
The c# function-
protected void Sess(string id)
{
Session["forDelete"] = id;
}
You can create a web method
[WebMethod(EnableSession = true)]
public static Application GetApplication(int id)
{
}
and in javascript you then do something like this
$.ajax(
{
type: "POST",
url: "Applications.aspx/GetApplication",
contentType: "application/json; charset=utf-8",
data: "{'id':" + id + "}",
dataType: "json",
success: methodToDoSomethingOnSuccess,
error: function (rhq, textStatus, errorThrown) {
alert ("some went awry");
}
});
you have to create an input of type submit that invokes your C# function using the HTML and make it hidden. Then create a div tag and using javascript do this:
#CSS
.Hidden {
display:none;
}
#HTML
<input type="submit" id="SubmitTag" OnClick="C# Functin" class="Hidden" runat="server" />
//if using MVC and Razor
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post)) {
<input type="submit" id="SubmitTag" class="Hidden" />
}
<div id="OnDivClick"> what you want to do in here </div>
#JS
$('#OnDivClick').click(function () {
$('#SubmitTag').trigger("click");
});
Well, there are ways to do this but I believe that you're trying to save something in the Session for the Delete.aspx page to read it. The simplest solution is just post the data in:
var form = document.createElement("form");
form.setAttribute('method', 'post');
form.setAttribute('action', 'Delete.aspx');
form.setAttribute('target', '_blank');
form.innerHTML = '<input type="hidden" name="forDelete" value="' + idimg + '" />';
document.body.appendChild(form);
form.submit();
This dynamically creates a form and submits it with idimg which will open the page Delete.aspx in a new window.
All that's left to do is go to the C# part of Delete.aspx page and catch the incoming data:
string idimg = Request.Form["forDelete"];
// Do whatever with it
Session["forDelete"] = idimg; // If you still want to save it in Session

How to call code behind method from a javascript function?

I am having an javascript function for a HTML img click event in aspx page. And a server Method in its code behind page.Now I want to call the server method from the javascript function without any parameter only when the HTML img is clicked by the user.
C# Code Behind Method:
[WebMethod]
public void PopUpClick(object sender, EventArgs e)
{
//Something;
}
JavaScriptMethod:
$(document).ready(function () {
$('.clickme').click(function () {
PageMethods.PopUpClick();
});
});
Also I added into the master page: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />
It is not working.When I debugging this Javascript function on the Chrome
I saw an error:Uncaught Reference Error:PageMethods is not defined.
.aspx
<div>
<p>Say bye-bey to Postbacks.</p>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
JavaScript
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
C#
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
The WebMethods that are defined must be "static".
The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!!
$.ajax({
type: "POST",
url: 'GenerateEAInHtml.aspx/GetAllRegions',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
});
The WebMethod is defined this way:
[WebMethod]
public static List<Region> GetAllRegions()
{
/* Your Code goes here */
return regions;
}
You might want to use this Ajax Post to also pass JSON data to the WebMethod by passing the data parameter!! This should help.
Assumption that your page name is abc.aspx and xyz is the function name that you have to call.
javascript :
function sendData(offset) {
$.ajax({
type: "POST",
url: "abc.aspx/xyz",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Server Side : add Imports System.Web.Script.Serialization
WebMethod(enableSession:=True) _
Public Shared Function xyz() As String
your code here
End Function
Add module in web.config -> system.webServer
->system.webServer>
->modules>
->add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
->/modules>
->/system.webServer>
Back end C# code is separate from your front end JavaScript code. JS runs on the client side and C# runs server side. In order to have front end code fire off a back end functions, you would either need your function to do a form postback or use Ajax (or an equivalent) to call that pages function.
Try this
[WebMethod]
public static void PopUpClick(object sender, EventArgs e)
{
//Something;
}
Use an ImageButton. The handler does not need to be tagged as [WebMethod]
<asp:ImageButton runat="server" ID="btnPopUp" ImageUrl="img.png" OnClick="PopUpClick" />
Why do you want to use img directly?
There is a line at the top that says uncomment this to call it by JavaScript.
Uncomment that.
Then also add a [ScriptMethod] to your method like this:
[WebMethod]
[ScriptMethod]
public void PopUpClick(object sender, EventArgs e)
{
// Something;
}
You should then be able to call it from the PageMethods object.
However I've just done some research and it seems that you may need to place your code that uses PageMethods at the end / after the ScriptManager as its possible you are trying to use PageMethods before its been declared in the JavaScript. Alternatively if you're using jQuery then you can do it in the ready event so you know the page and everything has loaded. I think this will probably turn out to be the root cause.
A web method has to be declared as static and public.
Although you can't access the page directly, you can either pass what you need into the web method from the call in your client side code, or store what you need in session or a similar state storage mechanism that is accessible from your static web method.
That may require re-thinking what you're trying to do with it.

Pass variable value calling c# behind function with javascript in asp.net

this is my scenario: I have an asp website that can merge tiff file. So, to do this i need to use a c# function and it is called after a javascript event.
The c# is like this:
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
I created two hidden field like this:
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" />
to get the value to pass at the function, because I didn't know in which way I can pass js variable to it.
I call the function in this way:
'<%mergeImages(par1,par2); %>';
In which way can I pass variable value to the function?
Decorate the method with WebMethod Attribulte:
[WebMethod]
public void mergeImages(string initialUrl, string lastImageUrl)
{....}
Get the hidden fields, and pass these to Jquery Ajax call, from a button click
var hdn1 = $('#hi1').val();
var hdn2 = $('#hi2').val();
var parameters = '{initialUrl:' + hdn1 + ', lastImageUrl:' + hdn2 + '}';
$.ajax({
type: "POST",
url: "page.aspx/mergeImages",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
}
});
Refer the stackoverflow thread.
ASP.NET - Passing JSON from jQuery to ASHX
This will help you to understand to use handler file (ashx) to do ajax json request.
your requirement can be achieved with this concept.
you do not need to call cs method into javascript. you should post using ajax on any kind of handler file e.g ashx, asmx, or any other service .
Nothing to do much you just need to take an extra button which will be hide in output:
<asp:button id="btnGetAndPassvalues" runat="server" Text="hide" Onclick="btnGetAndPassvalues_Click" Style="display:none"/>
Now javascript function should be like below:
<script>
$('[id$=btnUpload]').live('click', function (e) {
// code to finish Upload prosess
$('[id$=btnGetAndPassvalues]').click();
});
</script>
That's all and in click event get the values of hidden field:
protected void btnGetAndPassvalues(Object sender,EventArgs e){
string hd1=hiden1.Value;
string hd2=hiden2.Value;
}
or you can make AJAX Call,
one of the easy way to achieve this :-
As you already have two hidden fields but must add runat attribute to it ,so that
you can get their values at server side. Let's Say:-
<input type="hidden" id="hi1" value="D:\\ProvaUpload\\1.tif" runat="server" />
<input type="hidden" id="hi2" value="D:\\ProvaUpload\\2.tif" runat="server" />
and Make a hidden button :-
<asp:button id="btnhidden" runat="server" Text="hide" Onclick="btnhidden_Click" Style="display:none"/>
Now you can click the button in javascript function :-
function UploadFinished()
{
//your JS code:-
// After finish uploading ..Click the button .. i have used jquery for simplicity:-
$('input[id$="btnhidden"]').click();
}
Now in your code behind :-
protected void btnhidden_Click(Object sender,EventArgs e)
{
// you can get hidden fields values here ....
string val1=hi1.Value;
string val2=hi2.Value;
// Call your merge function here :-
mergeImages(val1,val2);
}

Open jQuery UI Dialog from Code Behind

I am kind of new with jQuery and JavaScript, and I ran into a problem.
I am having some problems to open the jQuery UI Dialog Box from my ButtonField within the Gridview:
<asp:ButtonField ButtonType="link" Text="Modify Deadline" Visible="true" runat="server" CommandName="modifyDeadline" ControlStyle-CssClass="button" ItemStyle-CssClass="sliderPopupOpener"/>
At first I tried to give a class to the above and named it sliderPopupOpener, and make it open the jQuery Popup when clicked as below:
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
However, this was not working because of the postback, apart from that, it also does not work with my approach. Since I would like to get some data from the database before showing the jQuery UI Dialog. So I think the best approach is to call the Dialog function from the Code Behind.
How can I do this?
I tried this approach, but it did not work, I am not sure if I am doing something wrong.
if (e.CommandName == "modifyDeadline")
{
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
ClientScript.RegisterStartupScript(typeof(Page), "key", sliderPopupFunction);
}
Is the above possible? If so, what am I doing wrong?
EDIT:
I noticed everyone is giving their answers with a way around this, rather than telling me whether this is possible just by calling the jQuery function from the Code Behind. Although I appreciate other solutions, I would appreciate if I could get this to work, with the least effort possible, through the code behind, since I have everything ready that way.
Instead of directly bind the click event handler, you should try delegated events using live (deprecated since jquery 1.7) or on.
That way, you should change this :
$(".sliderPopupOpener").click(function () {
$("#sliderPopup").dialog("open");
});
Into something like this :
$(body).on("click", ".sliderPopupOpener", function(){
$("#sliderPopup").dialog("open");
});
alternative
If the code-behind approach is more suitable for you, you should try calling the method directly in your script, i.e, change this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(function () {
jQuery(function () {
$(""#sliderPopup"").dialog(""open"");
}
});
</script>";
into simply this :
string sliderPopupFunction = #" <script type=""text/javascript"">
$(""#sliderPopup"").dialog(""open"");
</script>";
Also, if your sliderPopup is a server-side control, you should replace the #sliderPopup with the client Id generated by ASP .NET (using sliderPopup.ClientID).
Another thing to consider is if your sliderPopup located inside the update panel, you should try re-initialize the Jquery UI dialog first, something like this :
$("#sliderPopup").dialog().dialog("open");
Just Replace the <asp:ButtonField with <asp:TemplateField the write whatever you want:
<asp:TemplateField>
<ItemTemplate>
<input type="button" onclick='jsFunctionThatShowsTheDialog()'/>
</ItemTemplate>
</asp:TemplateField>
I think in this situation it would be better for you to use a plain old <input type="button/> button and use ajax to perform your call to the server, and then with the returned data append it to your html and use the dialog. Ajax will perform your code behind without posting back your entire page.
EDIT: here is an example I did a while ago
//declaring the web method annotation allows this method to be accessed by ajax calls
//scriptmethod tells this method to take the data that we're returning, and encode it as a json so we can use it in javascript
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Person> getPeople() {
List<Person> people = null;
using (testDataEntities context = new testDataEntities()) {
people = context.People.ToList();
}
return people;
}
$(document).ready(function () {
$("#getPeople").click(function () {
$.ajax({
type: "POST",
data: {},
url: "Default.aspx/getPeople", //getPeople is the name of the method
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = msg.d;
var $table = $("<table></table>");
$.each(data,function(){
$table.append("<tr><td>"+this.MyProperty+"</td></tr>")
});
$table.dialog();
}
});
});
});

PageMethods returning undefined result?

I have a very simple call to a PageMethod. When I step through my PageMethod in my .cs file, the value looks as expected. However, on the client side I get an undefined result. Any ideas? This should be horribly simple.
Here is my js: (EnablePageMethods="true" in my ASPX page)
function test() {
alert(PageMethods.MyMethod("Joe Blow"));
}
And here is my C#:
public partial class test : System.Web.UI.Page
{
[WebMethod]
public static string MyMethod(string name)
{
return "Hello " + name;
}
}
Here is the answer on how to call PageMethods using MS Ajax. First make sure you have downloaded the latest Ajax library from the MS website.
<asp:ScriptManager ID="sm1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<input type="button" value="Greeting" onclick="greetings()" />
<script language="javascript" type="text/javascript">
function greetings() {
PageMethods.GreetingFromPage(function(response) {
alert(response);
});
}
</script>
[WebMethod]
public static string GreetingFromPage()
{
return "greeting from page";
}
That is pretty much it!
You've to pass in a callback function that would be executed on Success / Exception. So in this case, it would be something like this
PageMethods.MyMethod("Joe Blow", onSuccess, onError);
function onError(desc) {
}
function onSuccess(result) {
}
I would check the documentation for the exact usage.
Check out the following screencast. It explains how to call the PageMethods using JQuery:
http://www.highoncoding.com/Articles/430_Calling_Page_Methods_Using_JQuery_and_Returning_JSON_Result.aspx
This is a great and concrete article on the subject.
For me, the following code is working.
I have a page that processes an excel file asynchronously; while processing, the function EsperarFinDelCargue() polls a PageMethod called CargueFinalizo()
each second to see if processing has ended. When processing finishes, a redirection takes place.
OnCallFinalizoComplete is the callback function for the PageMethod invocation, so there is where you need to use the resulting object.
<script type="text/javascript">
function EsperarFinDelCargue()
{
PageMethods.CargueFinalizo(OnCallFinalizoComplete);
if($('#<%=this.hidCargueFinalizado.ClientID %>').val() == "SI")
{
document.location = "CargarPanelHCP.aspx";
}
else
{
var t=setTimeout("EsperarFinDelCargue()",1000);
}
}
function OnCallFinalizoComplete(result,contexto,CargueFinalizo)
{
$('#<%=this.hidCargueFinalizado.ClientID %>').val(result);
}
</script>
And here is the PageMethod code in the aspx:
[System.Web.Services.WebMethod]
public static string CargueFinalizo()
{
//Whatever you need
return HttpContext.Current.Session["ResultadoCarguePanel"] != null ? "SI" : "NO";
}
Try This it will work fine
<script type="text/javascript">
function Generate()
{
var result = PageMethods.GenerateOTP(your parameter, function (response)
{
alert(response);
});
}
</script>

Categories

Resources