Using Jquery and Ajax in ASP.NET
I am using ajax and jquery to load contents into a div.
My jquery looks like this
$("a.trigger").click(function() {
$.ajax({
type: "POST",
url: "GetStuff.aspx",
data: "id=0",
success: function(response){
$("#contentDiv").html(response);
}
});
});
In GetStuff.aspx I would like to write some asp.net html controls like
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();
}
However the label does not appear on the p开发者_如何学Cage.
I tried to put the asp:Label in my aspx file like this
<%@ Page Language="C#" Inherits="Untitled.GetStuff" %>
<asp:Label id="label12" runat="server" text="helloworld2"/>
It also does not work. How can I get asp.net html controls to show up?
You can't. You're trying to add a server side control to a client side page. Try returning this instead:
Response.Write("<span id=\"label1\">helloworld</span>);
However, when you postback the page you won't have the luxury of being able to say
string text = label1.Text; //DOES NOT WORK
You are trying to write an ASP.NET Server Control as the output? You're actually overcomplicating things =D
If you wrote out
<span>HelloWorld</span>
Instead of the
<asp:Label Id="label1" runat="server" text="HelloWorld" />
You would get what you want. When you write to the response stream, you need to write valid HTML / Text, whatever. An ASP.NET Label is only transformed into a <span> when it's render function is called as part of the ASP.NET Life Cycle.
Just treat GetStuff.aspx as a regular page. Put your HTML in the .aspx, and any business logic in the Page_Load. It will then output HTML that your ajax call can use.
updated:
Your GetStuff.aspx page would be something like:
<%@ 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>
Then your codebehind GetStuff.aspx.cs would contain:
protected void Page_Load(object sender, EventArgs e)
{
var id = Request["id"].ToString();
this.idToDisplay.Text = id;
}
Of course your Page_Load can do a database query or whatever.
精彩评论