ASP.NET Call C# Functions From JavaScript - c#

I Have a small working application on ASP.NET and C# and I would like to add some Javascript to it.
I know that for example I can use the Confirm button and then do something on yes or no.
What I would like to do is call some of the functions I have in the code-behind, depending on the answer to the Confirm Button.
How do I go about this?
Many Thanks!

Simple.
Put a hidden div on your aspx page that contains button triggers to your methods:
<div style="display: none">
<asp:Button ID="TriggerMethod1" runat="server" />
</div>
In your javascript, in the confirm part of your code simply do:
__doPostBack('TriggerMethod1', '');
And in your code-behind, handle up that button click to call Method1.

I would create an ASHX handler file and post back to the hander using jQuery ajax methods.
See an article on this here:
Using jQuery in ASP.NET apps with httphandlers

To call a server side method on a client side event you need to do the following:
1- Create the server side method:
void DoSomething(...) { ... }
2- Implement the System.Web.UI.IPostBackEventHandler.RaisePostBackEvent which take one string argument (You can assign the name to the value of this argument).:
public void RaisePostBackEvent(string eventArgument)
{
DoSomething(...);
}
3- Write a script to trigger post back:
function TriggerPostBack(control, arg){
__doPostBack(control, arg);
}
4- Call the PostBack trigger function when needed:
<a .... onclick="TriggerPostBack('control', 'arg')" .. />

Have you tried to use the search first in the site!!
Call ASP.NET function from JavaScript?
Calling functions from an ASP.NET code file with javascript
or https://stackoverflow.com/search?q=Call+C%23+Functions+From+JavaScript

Related

Need to call code behind method from Javascript without using ajax in asp.net

I need to call server side method in code behind file from javascript. Yes i know ajax is the best way to achieve this. But i am not able to use ajax bcoz i exported excel file and get download in server side method. In ajax request we not are able to download/upload files. So kindly suggest any other way to call server side method in code behind from client side. I am also able to achieve this using web service. But i need the functionality in code behind file. I need the functionality like MVC form, in mvc form we are able to give control and action name and make form submit.
Add following HTML on page:
<asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' />
<asp:Button ID=”btnSave” runat=”server” Text=”Save” OnClientClick=”return CodeBehindMethodCall();” />
Now time to adjust our code behind so we can call it from JavaScript, we need to use System.Web.Services so add it in our code behind file
using System.Web.Services;
Whatever method we need to call from JavaScript, add WebMethodattribute to that method and that will easily be called by javaScript
[WebMethod]
public String ConvertDataTabletoString()
{
// your code
}
Now we will call ConvertDataTabletoString from JavaScript, so add the following JavaScript to the page:
function CodeBehindMethodCall()
{
pageName.ConvertDataTabletoString();
}
As you can see we have not used web service but we changed a method to web method so it can be called from JavaScript but without converting a method into web method we can not call any code behind method from JavaScript.
This is how its done.

Call a program inside a .cs file from a javascript function for onkeypress function ASP.net

I am trying to create a textbox which updates the text in it after a key has been pressed, so I have created a program inside the class of the page which executes the function I want. The program works fine, my question is how do I call that program in the javascript function when onkeypress event happens:
//My text box:
<asp:TextBox ID="MyBox" onkeypress="AutoText(); return false;" runat="server"
Width="400px" ToolTip="Text?" CausesValidation="True" AutoPostBack="True">
</asp:TextBox>
//My function
function AutoText()
{
var i;
i = Class1.BoxTextChanged(object sender, EventArgs e);
}
I know the function doesn't work and that's not how to call a program from a c# class in JavaScript, I am only asking if it's possible how to do it.
Note that I did research this as much as I can, maybe the searches I did were of no use because there are so many subjects to this topic or maybe I just did it wrong :P
You are mixing client and server side. ASP.NET is executed from server side, and Javascript is executed from client side.
So, you cannot call an ASP.NET function directly from Javascript in your case, because the server cannot access to the client side textbox.
Your solution is to write this function in Javascript. It could be something like that :
function boxTextChanged(text) {
getElementById('textBoxToUpdate').value(text);
}
By the way, I just want to add that you can call ASP.NET directly in Javascript using ajax, but server side will never be able to update directly DOM on the client side. Usually, ajax is used to get datas from server.
you can call the web method onkeypress envt and pass it the value of text box which will update the database with text box value.
which is done by javascript so that you did not required post back of whole page so it improve your performance.

pass parameter to one function in the code behind in C# from javascript

I am trying to pass parameter to one function in the code behind in C# from javascript
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. That id is not defined in this context.
Can some please let me know what wrong i am doing?
First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.
Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value.
Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click.
The button click event in C# will be triggered by Postback when your browser post data back to asp.net
I do not understand why you use HiddenField here,so my suggestion do not consider about it
Solution 1:
first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js
sample code is here
Solution 2:
if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform

Adding javascript functions to asp control

iv'e got an asp button which performs another task besides postback
i have done this by adding javascript code to the button as follows
if( !IsPostBack )
btn1.Attributes.Add("onclick", "f();");
i'm not sure of 2 things
the first :
where in the cs code i should add the function f() , currently i'm doing it in page load
while ignoring postbacks because then the function would have already been added(i might be wrong)
the second :
is there any to make the function execute only if the page was validated ? (after postback)
thanks in advance
eran.
I would use OnClientClick instead of adding the click event throug the attributes. As for your JavaScript, I would add it in the ASPX part. Depending on what the function does, you might be able to avoid the code behind all together and do something like this:
<asp:Button ID="Button1" runat="server" Text="Hi" OnClientClick="javascript:return f();" OnClick="Button1_Click" />
From your f() function, kick off the validation, and return true if validation passes, otherwise return false. If OnClientClick returns true the page will post back, and if it returns false the page will not post back.
1st Question
You will need to add it each time.
btn1.Attributes.Add("onclick", "f();");
2nd Question
You can check the validity of a page by checking the Page.IsValid Property
Unobtrusive JavaScript
If you're serious about javascript then you don't want to write inline javascript.
You will want to create an event handler in javascript code inside the script tags or in a external file.
If you're using .NET 4 server control id:s will be good, else I would use jquery's
contains selector. Search for the given server control ID.

Javascript for running code-behind code when a button is clicked

i have a popup that is getting displayed when Save button is clicked. The popup has 2 buttons. Yes and No. No should cancel the popup
and yes should take you to function in the code-behind say, btnSave_Click(object sender, Eventargs e). How is it possible. Could someone help me, i am new to Javascript.
Below is the code where i am showin the popup.
var mdlPopup = $find('<%= ModalPopupExtendersavechanges.ClientID %>');
if(mdlPopup)
{
mdlPopup.show();
}
To do this you will need to set your server side function as a web method like this:
Add to the top of your code behind:
using System.Web.Services;
using System.Web.Script.Services;
Then decorate your method with these attributes:
[WebMethod(), ScriptMethod()]
public static void btnSave_Click(Object sender)
{
//Stuff
}
To call this from the client side (Javascript) do this:
PageMethods.btnSave_Click(this,btnSave_Click_Finished);
You can place that in a client click event. The first argument is the sender parameter, the second is the javascript function to call when the server side method has completed.
You can't call server side code from JavaScript directly. Make a postback or fire a XHR (AJAX) request in the background.
I think it is possible for you to acess the serverside script by using javascript.
__doPostBackis a function which is behind the asp postback and this function is called when a button is clicked or dropdown value is changed.
For more details pls refer to [this.][1]
All you need is to place a <asp:Button ID="btnSave" runat="server" onClick="btnSave_Click" /> in the form and in the javascript (ie button click function) just call the __doPostBack('<%= btnSave.UniqueID %>', '');
So it will calls the serverside function.(btnSave_Click)
Notice that you need to give '<%= btnSave.UniqueID %>' as the firstargument.
The above will works as similar to a server button click
The another way is to make a post or ajax using jquery.post or jquery.ajax it is possible to send request asynchronously to the server.Here you want to pass some query string and call the appropriate function in the page_Load
This will do without any postback
One another method is to use PageMethods from clientside by defining a static WebMethod
[1]: http://msdn.microsoft.com/en-us/library/aa720099%28vs.71%29.aspx/"Call serverside function from clientside"
I hope any one of these will solve your problem
the Yes button should be an asp.net control with a server-side handler
markup
<asp:button id="yesButton" runat="server" onclick="yes_click" />
codebehind
void yes_click(object sender, EventArgs e) {
// TODO your thing here.
}
the other buttons can be standard html inputs with javascript event handlers. if you are using javascript to alter element style, the changes won't persist across a postback- when the yes button submits and the page reloads, the popup won't be visible.

Categories

Resources