To call C# Function from Javascript in Web apps - c#

Hi i wanted to call a C# function through javascript code.
For Eg: i have C# function which is in aspx.cs page
public void setValue()
{
lblMsg.Text = "hello";
....
.....
}
from javascript i need to call this function.

This is not possible directly indeed. If you are using Web Forms you can have a C# button handler which will change text of your label in server side and then you can call the _doPostBack function for that handler.

Somehow you have to do as postback, either complete or partial. Use AJAX (UpdatePanel)

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.

Executing Server-Side Methods by Clicking on a DIV

I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work

ASP.NET Call C# Functions From JavaScript

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

To get controls inside static function

I am calling function in codebehind from javascript using webservice.
function GetAdmissionType()
{
InitComponents();
var type="";
type=document.getElementById(dlAdmissionType.id).value;
document.getElementById(hdnAdmissionType.id).value=document.getElementById(dlAdmissionType.id).value;
else if(type=="2")
{
InitComponents();
ViewResettingPanel()
makeFavorite(1);
}
}
function makeFavorite(id) {
PageMethods.SaveInfo(id, CallSuccess, CallFailed);
}
// This will be Called on success
function CallSuccess(res, id) {
alert(destCtrl);
}
// This will be Called on failure
function CallFailed(res) {
alert(res.get_message());
}
Following is my code in codebehind
[System.Web.Services.WebMethod]
public static void SaveInfo(String Id)
{
//to get textbox in form
}
Problem is iam not getting controls in aspx page in SaveInfo.Can anybody help to access controls in form inside saveinfo?
Static page methods cannot get the page's control tree. (They don't receive ViewState)
You will need to use an UpdatePanel.
You can make an asp:Button inside a <div style="display:none> with a regular Click event, make an UpdatePanel triggered by the button, and use Javascript to simulate a click of the button.
Alternatively, you could send the values of the controls that you need as parameters to your page method in Javascript. This will be more efficient than using an UpdatePanel.
You can't.
Your WebMethod is static, meaning it exists once, for all instances of your page class. It has no notion of any individual instance of your Page.
If you need to post your page back, you'll need to actually use postbacks, and not web service calls.

Categories

Resources