Call ASP.NET Function From Javascript?

Question!

I'm writing a web page in ASP.NET. I have some JavaScript, and I have a submit button with a click event.

Is it possible to call a method I created in ASP with JavaScript's click event?

By : MattSayar


Answers

Please try this..

<%= Page.ClientScript.GetPostBackEventReference(ddlVoucherType, String.Empty) %>;

ddlVoucherType is control which selected index change will call....And you can put any function on the selected index change of this control.



var button = document.getElementById(/* button client id */);

button.click();

It should be like:

var button = document.getElementById('<%=formID.ClientID%>');

Where formID = asp.net control ID in aspx file

By : KDJ


I think this will help you

http://dotnetawesome.blogspot.in/2013/12/how-to-fetch-show-sql-server-database-data-using-ajax-jquey.html

Javascript Code

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript">
    function GetCompanies() {
        $("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCompanies",
            data: "{}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: OnError
        });
    }
    function OnSuccess(data) {
        var TableContent = "<table border='0'>" +
                                "<tr>" +
                                    "<td>Rank</td>" +
                                    "<td>Company Name</td>" +
                                    "<td>Revenue</td>" +
                                    "<td>Industry</td>" +
                                "</tr>";
        for (var i = 0; i < data.d.length; i++) {
            TableContent += "<tr>" +
                                    "<td>"+ data.d[i].Rank +"</td>" +
                                    "<td>"+data.d[i].CompanyName+"</td>" +
                                    "<td>"+data.d[i].Revenue+"</td>" +
                                    "<td>"+data.d[i].Industry+"</td>" +
                                "</tr>";
        }
        TableContent += "</table>";

        $("#UpdatePanel").html(TableContent);
    }
    function OnError(data) {

    }
</script>

ASP.NET Server Side Function

[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
    System.Threading.Thread.Sleep(5000);
    List<TopCompany> allCompany = new List<TopCompany>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        allCompany = dc.TopCompanies.ToList();
    }
    return allCompany;
}
By : SRV


This video can help you solving your question :)
By: admin