[英]Using Jquery and Ajax in ASP.NET
我正在使用ajax和jquery將內容加載到div中。
我的jQuery看起來像這樣
$("a.trigger").click(function() {
$.ajax({
type: "POST",
url: "GetStuff.aspx",
data: "id=0",
success: function(response){
$("#contentDiv").html(response);
}
});
});
在GetStuff.aspx中,我想編寫一些asp.net html控件,例如
private void Page_Load(object sender, System.EventArgs e)
{
Response.Expires = -1;
Response.ContentType = "text/plain";
Response.Write("<asp:Label id=\"label1\" runat=\"server\" text=\"helloworld\"/>");
Response.End();
}
但是標簽不會出現在頁面上。
我試圖像這樣將asp:Label放在我的aspx文件中
<%@ Page Language="C#" Inherits="Untitled.GetStuff" %>
<asp:Label id="label12" runat="server" text="helloworld2"/>
它也不起作用。 我怎樣才能顯示asp.net html控件?
你不能 您正在嘗試將服務器端控件添加到客戶端頁面。 嘗試返回以下內容:
Response.Write("<span id=\"label1\">helloworld</span>);
但是,當您回發頁面時,您將無法說
string text = label1.Text; //DOES NOT WORK
您正在嘗試將ASP.NET服務器控件編寫為輸出嗎? 您實際上使事情復雜化= D
如果你寫了
<span>HelloWorld</span>
而不是
<asp:Label Id="label1" runat="server" text="HelloWorld" />
您會得到想要的。 寫入響應流時,無論如何都需要編寫有效的HTML /文本。 僅當將ASP.NET標簽的呈現函數作為ASP.NET生命周期的一部分調用時,它才會轉換為<span>。
只需將GetStuff.aspx視為常規頁面即可。 將您的HTML放在.aspx中,並將任何業務邏輯放在Page_Load中。 然后它將輸出您的ajax調用可以使用的HTML。
更新:
您的GetStuff.aspx頁面將類似於:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetStuff.aspx.cs" Inherits="GetStuff" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label Id="label1" runat="server" text="Hello World" />
<asp:Label Id="idToDisplay" runat="server" />
</div>
</form>
</body>
</html>
然后,您在GetStuff.aspx.cs后面的代碼將包含:
protected void Page_Load(object sender, EventArgs e)
{
var id = Request["id"].ToString();
this.idToDisplay.Text = id;
}
當然,您的Page_Load可以執行數據庫查詢或其他任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.