Call ASP.NET Function from JavaScript

Call ASP.NET function from JavaScript?

Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries):

It is a little tricky though... :)

i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like

public partial class Default : System.Web.UI.Page, IPostBackEventHandler{}

ii. This should add (using Tab-Tab) this function to your code file:

public void RaisePostBackEvent(string eventArgument) { }

iii. In your onclick event in JavaScript, write the following code:

var pageId = '<%=  Page.ClientID %>';
__doPostBack(pageId, argumentString);

This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like.

P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!

Calling JavaScript Function From CodeBehind

You may try this :

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

How to call a codebehind function from javascript in asp.net?

in JavaScript:

    document.getElementById("btnSample").click();

Server side control:

    <asp:Button runat="server" ID="btnSample" ClientIDMode="Static" Text="" style="display:none;" OnClick="btnSample_Click" />

C#

    protected void btnSample_Click(object sender, EventArgs e)
{

}

It is easy way though...

calling ASP function from javascript

Define your method in a class somewhere in your web application.

[System.Web.Services.WebMethod]
public static string Msg()
{
return "Hello world";
}

Add a script manager with EnablePageMethods=true in your aspx page

<asp:ScriptManager ID="someId" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Call the method in javascript

<script language="javascript" type="text/javascript">
PageMethods.Msg(onSuccess);
function onSuccess(response)
{
alert(response);
}
</script>

How to call a Server Side Function in a javascript Function

You can achieve this in 2 ways. Ajax/Web Service or triggering button click in JS. Most simplest is to trigger button click. Use following code.

aspx:

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" ClientIDMode="Static" style="display:none;"/>

c#:

protected void Button1_Click(object sender, EventArgs e)
{
Delete();
}

JS:

document.getElementById('Button1').click();

// jquery
$("#Button1").click();

But if you do not want to postback your page then use Ajax.
In Ajax simple, you need to add a webpage say data.aspx, in backend class of data.aspx you to will add following c#

Ajax. C#

 [WebMethod]
public static int DoSomething(int Id)
{
return 1;
}

And now you can call this from JS:

$.ajax({
url: APP_PAGE_RELATIVE_PATH + "Data.aspx/DoSomething",
data: "{'Id':5}",
type: "POST",
cache: false,
headers: { "cache-control": "no-cache" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {

// Do Something

},
error: function (xhr, status, error) {
//DebugAlert("Error: " + xhr.responseText);
}
});

Call Model function from javascript in razor page

I agree with Mike Brind. At the same time, I also did some testing work, which I also shared.

We can't call C# function from javascript directly, Because javascript execute on client side and C# function execute at server side.
So we need to call it other way like AJAX.

Define your function in Model and call it via AJAX call.

JS Code:

<script>
function writeLog(msg) {
$.ajax({
url: '?handler=WriteLog&msg='+msg,
success: function (data) {
alert(data);
},
error: function (error) {
alert("Error: " + error);
}
})
}
</script>

Model Function Code:

public IActionResult OnGetWriteLog(string msg)
{
return new JsonResult(msg);
}

Test Results:

Sample Image

Sample Image

Call asp.net function with out button click from java script directly with out page refresh

As mentioned in the comment, you can easily do it with jquery ajax. For this you will have to define a WebMethod something like this:-

Please include using System.Web.Services;.

[WebMethod]
public static bool Check_exam_id(string className, string MethodName)
{
bool examIdExist = false;
if (DD__Method == "THEORY")
{
\\Your logic here
}
\\Based on DB operation return value
examIdExist
}

Finally call it from your client side like this:-

$("#Check_examid").click(function (e) {
e.preventDefault(); //To avoid postback
//Get these values from dropdwon
var className = $("#DD_class").val();
var methodName = $("#DD_Method").val();
var data = { "className": className , "MethodName": methodName };
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Check_exam_id",
data: JSON.stringify(data),
success: function (response) {
if(response.d) //If method returned true.
alert('Exist');
else
alert('No Student Found')
},
error: function (msg) { alert(msg.d); }
});
});

Also, include jquery base library file.



Related Topics



Leave a reply



Submit