How to call code behind method from a javascript function? - c#

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.

Related

Calling method from Master.cs on any aspx page using javascript on Master.Master

I want to offer a user discount (pop up) after 30 seconds being on site (any page). Since this project implements WebForms master page, I put the timer inside Master.aspx, and the method that communicates with db inside Master.cs. The method checks eligibility through calling stored procedure, and returns bool.
I set javascript timer inside aspx Master page, so after the time out, I want to call the method providing it userID. How can I call this isUserEligibleForDiscount method that's inside Master.cs using javascript?
setTimeout(function () {
if (sessionStorage.getItem('timer') == 'on') {
if (isUserEligibleForDiscount(userID)) {
$('#myModal').modal('show');
}
sessionStorage.setItem('timer', 'off');
}
}, 30000);
Use [WebMethod] attribute. It makes the method callable from remote Web clients (WebMethodAttribute Class).
Decorate your isUserEligibleForDiscount with that attribute.
You can then call the method via Ajax. You specify your page in the URL for the Ajax call: 'yourpage.aspx/isUserEligibleForDiscount'
You can put your method(s) into a page that does nothing but hold code, or you could call an asmx web service.
setTimeout(function() {
doAjaxPageMethodCall();
//if (sessionStorage.getItem('timer') == 'on') {
// if (isUserEligibleForDiscount(userID)) {
// $('#myModal').modal('show');
// }
// sessionStorage.setItem('timer', 'off');
//}
}, 3000);
function doAjaxPageMethodCall() {
$.ajax({
type: "POST",
// page-methods.aspx holds your methods.
// replace AjaxPageMethodCall w/ isUserEligibleForDiscount.
url: "/page-methods.aspx/AjaxPageMethodCall",
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(data) {
if(data.d===true) {
// show modal .
}
}).fail(function() {
$("#lbl").html("Houston...");
});
}
Of course you can combine the 2 functions, they're just split up for testing.
Web service is similar:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="/web-services/test-service.asmx" />
</Services>
</asp:ScriptManager>
And the only change to the ajax call is the url:
url: "/web-services/test-service.asmx/HelloWorld", ...
Your test-service.cs file will hold the actual methods.

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

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);
}
});
});

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();
}
});
});
});

How to call a Webservice function from masterpage

I want to open a html page when user presses a function key.
Now the capturing of the function key works fine, but the logic to open the appropriate page is written in Code-Behind of master page.
I read on internet that if I want to call function in code behind then I have to create a web- service and call the webservice method from master page.
But for some reason this is not working.May be I am not calling the web service properly.
Can some body please help?
Many Thanks
<cc1:ToolkitScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release" EnableHistory="true" EnableSecureHistoryState="false"
EnablePageMethods="true" CombineScripts="false">
<Scripts>
<asp:ScriptReference Path="~/ShowHelpPage.asmx" />
</Scripts>
</cc1:ToolkitScriptManager>
document.onkeydown = function(event){
if(window.event && window.event.keyCode == 113)
{
window.open("HelpFile/index.html");
}
else if(event.which == 113)
{
window.open("HelpFile/index.html");
DisplayHelpFile();
}
}
function DisplayHelpFile()
{
var i = PageMethods.DisplayHelpPage();// I think this is wrong
alert(i);
}
Web Method
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ShowHelpPage : System.Web.Services.WebService
{
[WebMethod]
public string DisplayHelpPage()
{
return "Window.Html";
}
}
"I read on internet that if I want to call function in code behind
then I have to create a web- service and call the webservice method
from master page"
I assume in the context you are refering to methods and not functions. Do you want to call a method when you master page loads? I would think that you dont need to create a Web Service for this? Unless you want the client to initiate the request through Async and you are using JavaScript and AJAX to make the request. What are you trying to achieve? It seems to me this can be achieved through just javascript. If you call a page through JavaScript it should load itself?
Below achieving what you want but using just javascript.
function keyHandler(e)
{
... key handling script
if(myKey == 'F1')
{
window.location.href = '...';
}
}
document.onkeypress = keyHandler;
If you need to call this Web Service and it needs to be initiated from the Client you could use JQuery to do this. Use the same approach with ShowHelpPage.asmx storing the processing and your rendering handled through JavaScript. This also to the best of my knowledge removes the dependency on ToolkitScriptManager.
function DisplayHelpFile()
{
$.ajax({
type: "POST",
url: "ShowHelpPage.asmx/DisplayHelpPage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(result)
{
alert(result);
}
},
error: ErrorMessage
});
function ErrorMessage(result)
{
alert(result.status + ' ' + result.statusText + ' ' + result.responseText);
}
}
Your web method needs to be static.

Categories

Resources