Call ASP.NET function from JavaScript?

2018-12-31 09:14发布

I'm writing a web page in ASP.NET. I have some JavaScript code, 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?

20条回答
无与为乐者.
2楼-- · 2018-12-31 09:39

You might want to create a web service for your common methods.
Just add a WebMethodAttribute over the functions you want to call, and that's about it.
Having a web service with all your common stuff also makes the system easier to maintain.

查看更多
泪湿衣
3楼-- · 2018-12-31 09:40

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!

查看更多
爱死公子算了
4楼-- · 2018-12-31 09:42

Static, strongly-typed programming has always felt very natural to me, so at first I resisted learning JavaScript (not to mention HTML and CSS) when I had to build web-based front-ends for my applications. I would do anything to work around this like redirecting to a page just to perform and action on the OnLoad event, as long as I could code pure C#.

You will find however that if you are going to be working with websites, you must have an open mind and start thinking more web-oriented (that is, don't try to do client-side things on the server and vice-versa). I love ASP.NET webforms and still use it (as well as MVC), but I will say that by trying to make things simpler and hiding the separation of client and server it can confuse newcomers and actually end up making things more difficult at times.

My advice is to learn some basic JavaScript (how to register events, retrieve DOM objects, manipulate CSS, etc.) and you will find web programming much more enjoyable (not to mention easier). A lot of people mentioned different Ajax libraries, but I didn't see any actual Ajax examples, so here it goes. (If you are not familiar with Ajax, all it is, is making an asynchronous HTTP request to refresh content (or perhaps perform a server-side action in your scenario) without reloading the entire page or doing a full postback.

Client-Side:

<script type="text/javascript">
var xmlhttp = new XMLHttpRequest(); // Create object that will make the request
xmlhttp.open("GET", "http://example.org/api/service", "true"); // configure object (method, URL, async)
xmlhttp.send(); // Send request

xmlhttp.onstatereadychange = function() { // Register a function to run when the state changes, if the request has finished and the stats code is 200 (OK). Write result to <p>
    if (xmlhttp.readyState == 4 && xmlhttp.statsCode == 200) {
          document.getElementById("resultText").innerHTML = xmlhttp.responseText;
    }
};
</script>

That's it. Although the name can be misleading the result can be in plain text or JSON as well, you are not limited to XML. jQuery provides an even simpler interface for making Ajax calls (among simplifying other JavaScript tasks).

The request can be an HTTP-POST or HTTP-GET and does not have to be to a webpage, but you can post to any service that listens for HTTP requests such as a RESTful API. The ASP.NET MVC 4 Web API makes setting up the server-side web service to handle the request a breeze as well. But many people do not know that you can also add API controllers to web forms project and use them to handle Ajax calls like this.

Server-Side:

public class DataController : ApiController
{
    public HttpResponseMessage<string[]> Get()
    {
        HttpResponseMessage<string[]> response = new HttpResponseMessage<string[]>(
            Repository.Get(true),
            new MediaTypeHeaderValue("application/json")
        );

        return response;
    }
}

Global.asax

Then just register the HTTP route in your Global.asax file, so ASP.NET will know how to direct the request.

void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapHttpRoute("Service", "api/{controller}/{id}");
}

With AJAX and Controllers, you can post back to the server at any time asynchronously to perform any server side operation. This one-two punch provides both the flexibility of JavaScript and the power the C# / ASP.NET, giving the people visiting your site a better overall experience. Without sacrificing anything, you get the best of both worlds.

References

查看更多
只靠听说
5楼-- · 2018-12-31 09:43

Add this line to page load if you are getting object expected error.

ClientScript.GetPostBackEventReference(this, "");
查看更多
后来的你喜欢了谁
6楼-- · 2018-12-31 09:44

I think blog post How to fetch & show SQL Server database data in ASP.NET page using Ajax (jQuery) will help you.

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;
}
查看更多
梦该遗忘
7楼-- · 2018-12-31 09:45

You can do it asynchronously using .NET Ajax PageMethods. See here or here.

查看更多
登录 后发表回答