InnerHTML attribute empty on span tag during page submit - jQuery/ASP.NET
I have a hidden TextBox
control on my page that updates a span
tag on the keyup
event using jQuery. When the page is posted back to the s开发者_运维百科erver, the innerHTML
attribute is empty.
How do I get the value that was set during the keyup
event?
Client side code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#MyHiddenTextBox').keyup(function(){
if($(this).val().length > 0){
SetSpanValue();
}
});
});
function SetSpanValue() {
var mytext = $('#MyHiddenTextBox').val();
$('#MySpanTag').html(mytext);
}
</script>
<style type="text/css">
.USBBox
{
position: absolute;
left: -999em;
}
</style>
<asp:TextBox ID="MyHiddenTextBox" runat="server" CssClass="USBBox" />
<span id="MySpanTag" runat="server" enableviewstate="true" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
Server side code
protected void btnSubmit_Click(object sender, EventArgs e)
{
string x = MySpanTag.InnerHtml; //this is coming back empty
}
Remember that asp.net is still built on top of html form submissions, and with html forms only input and select tags are submitted back to the server. So you need to make your javascript update an input of some type (hidden would work just fine) at the same time it updates the span.
Span tags are not posted back to the server, they are not input controls, regardless of runat
or enableviewstate
settings. I would recommend entering the data into an input element when entered into the span tag, then you can access the value of that input element (TextBox/HiddenField etc) when the postback occurrs.
The contents of the element are not sent to the server in a postback.
All EnableViewState="true"
does for you is tracks the changes made to the InnerHtml
on the server.
You'll need to put the data into a hidden input.
In addition to the fact that you cannot capture span values on postback (as others have answered)... ASP.Net will not accept values set via javascript for hidden form fields because it considers this a security threat.
I have gotten around this in the past by making the form field visible but hosting it inside a hidden div. Then you can set the value of the textbox and it will be posted back to the server.
<div style="display:none;"><asp:TextBox id="MyHiddenTextBox" runat="server" /></div>
精彩评论