Strange Problem with asp.net c# assigning string
i h开发者_高级运维ave a div element in my html,
<div id="userSolution" runat="server" text="1234512345123451234512345"></div>
Yes it does contain 25 characters,
i have a button:
<asp:Button id="saveGame" runat="server" text="Save Game" onclick="saveGame_Click" />
server Code:
protected void saveGame_Click(object sender, EventArgs e)
{
string clientInput = userSolution.Attributes["text"];
}
So why... when i debug, does clientInput
= "" ?
By my reckoning... text="1234512345123451234512345"
so string clientInput= userSolution.Attribute["text"];
should work right? :s
confused...
even if the div is:
<div id="userSolution" runat="server">1234512345123451234512345</div>
and i read
string clientId = userSolution.InnerHTML;
Still Fails
You can't post back the data that way in a div tag if you are setting the value of the div on the client side. You'll need to use a form element, like a hidden textbox if you want to use a straight ASP.NET postback.
Here's a simple example. It uses a javascript event to set the text of a HiddenField when the button is pressed and then displays the text on postback.
<%@ Page Language="C#" AutoEventWireup="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function copyToHiddenField() {
var hidden = document.getElementById("<%= txtHidden.ClientID %>");
var theDivText = document.getElementById("thedata").innerHTML;
hidden.value = theDivText;
return true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="thedata">Here's the data!</div>
<asp:HiddenField ID="txtHidden" runat="server" />
<asp:Button ID="btnSumbit" Text="Submit" OnClick="btnSumbit_OnClick" runat="server" />
<asp:Literal ID="litText" runat="server" />
</form>
</body>
</html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
btnSumbit.Attributes.Add("onclick", "return copyToHiddenField();");
}
public void btnSumbit_OnClick(object sender, EventArgs e)
{
litText.Text = txtHidden.Value;
}
</script>
EDIT
As stated in the answers/comments, you can use the InnerText
property of a div
tag when runat="server"
is specified, but you will only be able read out the InnerText
that is set when the page is rendered. Client side updates to the InnerText
of the div will not be sent to the server on postback.
Try InnerText, and also change
<div id="userSolution" runat="server" text="1234512345123451234512345"></div>
to
<div id="userSolution" runat="server">1234512345123451234512345</div>
Use the asp:panel. That should give you what you're after (a div in client and .Text in server code
Edit
Wow, it's been a while and I actually thought there was a Text property - I even checked old projects in disbelief!! :-/
精彩评论