Programing

JavaScript에서 ASP.NET 함수를 호출 하시겠습니까?

lottogame 2020. 6. 24. 07:58
반응형

JavaScript에서 ASP.NET 함수를 호출 하시겠습니까?


ASP.NET에서 웹 페이지를 작성 중입니다. JavaScript 코드가 있고 클릭 이벤트가있는 제출 버튼이 있습니다.

JavaScript의 클릭 이벤트로 ASP에서 만든 메소드를 호출 할 수 있습니까?


글쎄, Ajax 또는 다른 방법을 사용하지 않고 정상적인 ASP.NET 포스트 백을 원한다면 다른 라이브러리를 사용하지 않고 다음과 같이하십시오.

그래도 조금 까다 롭습니다 ... :)

나는. C # 및 .NET 2.0 이상을 사용한다고 가정 할 때 코드 파일에서 다음과 같은 인터페이스를 Page 클래스에 추가하십시오.

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

ii. 기능을 코드 파일에 추가 ( Tab- 사용 Tab) 해야 합니다.

public void RaisePostBackEvent(string eventArgument) { }

iii. JavaScript의 onclick 이벤트에서 다음 코드를 작성하십시오.

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

이것은 JavaScript에서 전달한 'argumentString'으로 'eventArgument'를 사용하여 코드 파일에서 'RaisePostBackEvent'메소드를 호출합니다. 이제 원하는 다른 이벤트를 호출 할 수 있습니다.

추신 : 그것은 '밑줄-밑줄-포스트 포스트'입니다 ... 그리고 그 순서에는 공백이 없어야합니다 ... 어떻게 든 WMD는 밑줄에 문자를 쓸 수 없습니다!


__doPostBack()방법은 잘 작동합니다.

또 다른 해결책 (매우 해킹)은 마크 업에 보이지 않는 ASP 버튼을 추가하고 JavaScript 방법으로 클릭하는 것입니다.

<div style="display: none;">
   <asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>

JavaScript에서 ClientID를 사용하여 버튼에 대한 참조를 검색 한 후 .click () 메소드 를 호출하십시오 .

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

button.click();

마이크로 소프트 AJAX 라이브러리는 이 작업을 수행합니다. AJAX를 사용하여 .NET 함수를 실행하기 위해 자체 aspx (기본적으로) 스크립트 파일을 호출하는 자체 솔루션을 만들 수도 있습니다.

Microsoft AJAX 라이브러리를 제안합니다. 일단 설치하고 참조하면 페이지로드 또는 초기화에 한 줄만 추가하면됩니다.

Ajax.Utility.RegisterTypeForAjax(GetType(YOURPAGECLASSNAME))

그런 다음 다음과 같은 작업을 수행 할 수 있습니다.

<Ajax.AjaxMethod()> _
Public Function Get5() AS Integer
    Return 5
End Function

그런 다음 페이지에서 다음과 같이 호출 할 수 있습니다.

PageClassName.Get5(javascriptCallbackFunction);

함수 호출의 마지막 매개 변수는 AJAX 요청이 리턴 될 때 실행될 JavaScript 콜백 함수 여야합니다.


.NET Ajax PageMethods를 사용하여 비동기 적으로 수행 할 수 있습니다. 여기 또는 여기를 참조 하십시오 .


블로그 게시물 Ajax (jQuery)를 사용하여 ASP.NET 페이지에서 SQL Server 데이터베이스 데이터를 가져오고 표시하는 방법 이 도움이 될 것이라고 생각합니다.

자바 스크립트 코드

<script src="http://code.jquery.com/jquery-3.3.1.js" />
<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 서버 측 기능

[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;
}

정적이고 강력한 형식의 프로그래밍은 항상 나에게 매우 자연스러운 느낌을 주었으므로 처음에는 응용 프로그램을위한 웹 기반 프런트 엔드를 구축해야 할 때 JavaScript (HTML 및 CSS는 말할 것도없이) 학습에 저항했습니다. 순수한 C #을 코딩 할 수있는 한 OnLoad 이벤트를 수행하고 조치를 취하기 위해 페이지로 리디렉션하는 것과 같이이 문제를 해결하기 위해 모든 작업을 수행합니다.

그러나 웹 사이트를 사용하려면 열린 마음을 가지고 더 웹 지향적 인 생각을 시작해야합니다 (즉, 서버에서 클라이언트 측 작업을 시도하지 마십시오) . 나는 ASP.NET 웹 양식을 좋아하고 여전히 MVC 뿐만 아니라 그것을 사용 하지만 클라이언트와 서버의 분리를 숨기려고하면 초보자를 혼란스럽게하고 실제로는 때로는 더 어려워 질 수 있다고 말할 것입니다 .

저의 조언은 기본적인 자바 스크립트 (이벤트 등록, DOM 객체 검색, CSS 조작 등)를 배우는 것입니다. 웹 프로그래밍은 훨씬 더 즐겁습니다 (쉽게 언급 할 수는 없습니다). 많은 사람들이 다른 Ajax 라이브러리를 언급했지만 실제 Ajax 예제는 보지 않았으므로 여기에갑니다. (Ajax에 익숙하지 않다면 전체 페이지를 다시로드하거나 전체 포스트 백을 수행하지 않고 컨텐츠를 새로 고치거나 시나리오에서 서버 측 작업을 수행하기 위해 비동기 HTTP 요청을하는 것입니다.

고객 입장에서:

<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>

그게 다야. 이름이 잘못 될 수 있지만 결과는 일반 텍스트 또는 JSON 일 수 있지만 XML로 제한되지는 않습니다. jQuery 는 Ajax 호출을위한보다 간단한 인터페이스를 제공합니다 (다른 JavaScript 작업을 단순화 함).

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


The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.

This is the library called AjaxPro which was written an MVP named Michael Schwarz. This was library was not written by Microsoft.

I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.


It is so easy for both scenarios (that is, synchronous/asynchronous) if you want to trigger a server-side event handler, for example, Button's click event.

For triggering an event handler of a control: If you added a ScriptManager on your page already then skip step 1.

  1. Add the following in your page client script section

    //<![CDATA[
    var theForm = document.forms['form1'];
    if (!theForm) {
        theForm = document.form1;
    }
    function __doPostBack(eventTarget, eventArgument) {
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }
    //]]>
    
    1. Write you server side event handler for your control

      protected void btnSayHello_Click(object sender, EventArgs e) { Label1.Text = "Hello World..."; }

    2. Add a client function to call the server side event handler

      function SayHello() { __doPostBack("btnSayHello", ""); }

Replace the "btnSayHello" in code above with your control's client id.

By doing so, if your control is inside an update panel, the page will not refresh. That is so easy.

One other thing to say is that: Be careful with client id, because it depends on you ID-generation policy defined with the ClientIDMode property.


I'm trying to implement this but it's not working right. The page is posting back, but my code isn't getting executed. When i debug the page, the RaisePostBackEvent never gets fired. One thing i did differently is I'm doing this in a user control instead of an aspx page.

If anyone else is like Merk, and having trouble over coming this, I have a solution:

When you have a user control, it seems you must also create the PostBackEventHandler in the parent page. And then you can invoke the user control's PostBackEventHandler by calling it directly. See below:

public void RaisePostBackEvent(string _arg)
{
    UserControlID.RaisePostBackEvent(_arg);
}

Where UserControlID is the ID you gave the user control on the parent page when you nested it in the mark up.

Note: You can also simply just call methods belonging to that user control directly (in which case, you would only need the RaisePostBackEvent handler in the parent page):

public void RaisePostBackEvent(string _arg)
{
    UserControlID.method1();
    UserControlID.method2();
}

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.


If the __doPostBack function is not generated on the page you need to insert a control to force it like this:

<asp:Button ID="btnJavascript" runat="server" UseSubmitBehavior="false" />

Regarding:

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

button.click();

It should be like:

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

Where formID is the ASP.NET control ID in the .aspx file.


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

ClientScript.GetPostBackEventReference(this, "");

You can use PageMethods.Your C# method Name in order to access C# methods or VB.NET methods into JavaScript.


Try this:

if(!ClientScript.IsStartupScriptRegistered("window"))
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "window", "pop();", true);
}

Or this

Response.Write("<script>alert('Hello World');</script>");

Use the OnClientClick property of the button to call JavaScript functions...


You can also get it by just adding this line in your JavaScript code:

document.getElementById('<%=btnName.ClientID%>').click()

I think this one is very much easy!


Please try this:

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

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


The simplest and best way to achieve this is to use the onmouseup() JavaScript event rather than onclick()

That way you will fire JavaScript after you click and it won't interfere with the ASP OnClick() event.


I try this and so I could run an Asp.Net method while using jQuery.

  1. Do a page redirect in your jQuery code

    window.location = "Page.aspx?key=1";
    
  2. Then use a Query String in Page Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["key"] != null)
        {
            string key= Request.QueryString["key"];
            if (key=="1")
            {
                // Some code
            }
        }
    }
    

So no need to run an extra code


This reply works like a breeze for me thanks cross browser:

The __doPostBack() method works well.

Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.

<div style="display: none;"> 
    <asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" /> 
</div> 

From your JavaScript, retrieve the reference to the button using its ClientID and then call the .Click() method on it:

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

button.Click(); 

Blockquote

참고URL : https://stackoverflow.com/questions/3713/call-asp-net-function-from-javascript

반응형