[英]How to call C# code from javascript function
在我的應用程序中,我需要調用aspx.cs方法來從javascript函數調用中綁定Gridview,我該怎么做?我搜索並找到了一些代碼,但是它對我不起作用
我嘗試了代碼:
客戶端:
<script>
function MyHeader() {
PageMethods.BindHeaderGrid(); //I tried this one also
var x = document.getElementById('HeaderDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
img2.src= "minus.gif";
} else {
x.style.display = 'none';
img2.src= "plus.gif";
}
}
</script>
<img id='img2' width="9px" border="0" src="plus.gif" onclick="MyHeader()"/> Header <div id="HeaderDiv" style="display:none">
<asp:GridView ID="GrdHeader" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="SenderID" HeaderText="SenderID" />
<asp:BoundField DataField="ReceiverID" HeaderText="ReceiverID" />
<asp:BoundField DataField="Transactiondate" HeaderText="Transactiondate" />
<asp:BoundField DataField="RecordCount" HeaderText="RecordCount" />
<asp:BoundField DataField="DispositionFlag" HeaderText="DispositionFlag" />
</Columns>
</asp:GridView></div>
服務器端:aspx.cs
[WebMethod]
public void BindHeaderGrid()
{
GrdHeader.DataSource = ds.Tables[0];
GrdHeader.DataBind();
}
謝謝
您不能這樣做-從客戶端在服務器端調用一個函數。
我看過您的代碼,有2個選項供您選擇:
如果您只想顯示或隱藏Gridview #GrdHeader,則可以始終在頁面加載時調用“ BindHeaderGrid”(或相同名稱)
如果要在用戶單擊#img2時重新加載Gridview,則可以將GridView #GrdHeader拆分為一個頁面,並通過iframe標記將其嵌入到此頁面,當使用click到img#img2時,僅重新加載iframe標記
檢查一下。
JavaScript的
$.ajax({
type: "POST",
dataType: "json",
data: {data: data}, // if no data available leave this out
url: "example.asmx/exampleMethod", //if you wanna call a function in the page just include the function name in here
success: function (data) {
// do something if the function is success
}
});
C#Web服務
public class Example: System.Web.Services.WebService
{
[WebMethod]
public void exampleMethod(Parameters)
{
// Something you wanna do
//If you wanna return something to javascript
Context.Response.ContentType = "text/HTML";
var js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(returnDataObject));
}
}
在你的情況下,我認為他可能會起作用。
$.ajax({
type: "POST",
dataType: "json",
url: "BindHeaderGrid()",
success: function (data) {
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.