According to the info in:
Which values browser collects as a postback data?
the value of the HTML input button is sent in a post back. I'm testing in ASP.NET with IE and I am not finding this to be the case.
The markup for my test case is:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" %>
<!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>test postback</title>
<script type="text/javascript">
function doTest() {
var button = document.getElementById("btnTest");
button.value = "new-value";
alert("button contents = " + button.value);
return true;
}
</script>
</head>
<body>
<form id="myForm" runat="server">
<div>
<asp:Panel ID="pnlTest" runat="server"
DefaultButton="btnTest">
Textbox:
<asp:TextBox ID="txtTest" runat="server" />
<asp:Button ID="btnTest" runat="server"
Text="change" OnClientClick="doTest()" />
</asp:Panel>
</div>
</form>
The code behind is:
Partial Class Test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
txtTest.Text = btnTest.Text
End Sub
End Class
My result is that the value of the input button is always "change" when the browser loads the page, but I was expecting it to be "new-value" after postback. The Javascript doTest() function is changing the value when the button is clicked.
Is there something more I'm supposed to do for ASP.NET or IE to get the input button value posted back? Or is the information about this functionality
wrong?
In a case like this I would probably use:
<input type="button" ID="btnTest" runat="server" onclick="doTest()" value="change" />
Note the runat="server".
While asp:button probably renders similarly, if what you really want it an HTML button input, you can use that. Yes, ASP.NET will pick up the value on the server side.
Also, do a view source and make sure the ASP.NET panel is not munging up the ID of the input. More generally, have you tested this without the asp:panel tag? I wonder if that affects anything.
I believe IE just hates input submits....
But you should also know...
ASP uses viewstate to ensure there is no tampering with server controls. The value of the submit button is stored in the view state and most likely the only way to modify the value of it is to use the ASP.NET JS API.
More commonly you see this problem with <selects> (Options added to by javascript lost in postback), but <input type="submit" /> is very similar
It's not that it's not being set, but the javascript sets the value, which gets reset back to "change" on the postback. If you're looking for a button that works with your javascript, use the client input control:
<input type="button" ID="btnTest" onclick="doTest()" />
Otherwise, if you want a server control, you should set btnTest.Text on the server side.
You are using the wrong id for the button. ASP.NET gives each control a unique id. It is made up of all the ids in the chain to your control.
Therefore your button probably has an id something like ctl00_pnlTest_btnTest. This is why your JavaScript is not setting the buttons text.
view source in your browser to see the actual ID of the control and adjust your JavaScript accordingly.
From code you can get the actual ID used in the page with the ClientID property. So you could change your JavaScript to:
var button = document.getElementById("<%= btnTest.ClientID %>");
Just tried Marc's solution like this:
<script type="text/javascript">
function doTest() {
var button = document.getElementById("btnTest1");
button.value = "new-value";
alert("button contents = " + button.value);
return true;
}
</script>
<input type="submit" id="btnTest1" name="btnTest1" value="Submit 1" runat="server" onclick="doTest()" />
When I posted back the Load event still had Submit 1 as the value of the button. You could use a hidden field, set that value with the button in JS and post back. That does in fact work.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>test postback</title>
<script type="text/javascript">
function doTest() {
var button = document.getElementById("btnTest1");
button.value = "new-value";
alert("button contents = " + button.value);
var hdn = document.getElementById("hdnTextboxName");
hdn.value = button.value;
return true;
}
</script>
</head>
<body>
<form id="myForm" runat="server">
<div>
<asp:Panel ID="pnlTest" runat="server" DefaultButton="btnTest">
Textbox:
<asp:TextBox ID="txtTest" runat="server" /><asp:HiddenField ID="hdnTextboxName" runat="server" ClientIDMode="Static" />
<asp:Button ID="btnTest" runat="server" Text="change" OnClientClick="doTest()" ClientIDMode="Static" />
</asp:Panel>
</div>
</form>
</body>
</html>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
txtTest.Text = hdnTextboxName.Value
End Sub
Related
i need help ;) i populate a ul with listitems from code behind trough Asp.net and htmlGenericControl.
The list items appear and these items are dropable and sortable into different uls trough jquery sortable and connectedSortable function. This works fine.
For example i have 3 lists. UnorderdLists(ul's) A, B and C.
List A is populated with a few items. Now i can drag and drop theses list items from list A to list B or C.
Now i need help how can i see or get (in/at codebehind) which item is in list B or C ?!
Info:
I dont use bulletlist because i think dropable/sortable would give me some trouble instead.
My ul's have added runat="server", do my li's have to had this aswell?
When I use a custom or not standard controls, I prefer to use hidden fields and store the data in a custom way (values with char separator for example).
You can populate via Javascript/Jquery your hidden fields at your specific events and then from codebehind you can read the hidden fields.
UPDATE with example
This is only one possiblity, but more simple probably is JQuery AJAX.
webform.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="webform.aspx.vb" Inherits="ajax_test.webform" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#send').click(function () {
$('#<%= HFTest.ClientID %>').val($('#theValue').val());
__doPostBack('<%= btn_force_async.ClientID %>','');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
// Fire before the AJAX request
}
function EndRequestHandler(sender, args) {
// Fire after the AJAX request
if ($('#<%=HFReturnMessage.ClientID %>').val() == 'ok') {
alert('ok!');
} else {
alert($('#<%=HFReturnMessage.ClientID %>').val());
}
}
</script>
<input id="theValue" type="text" value="ok" />
<input id="send" type="button" value="send value" />
<asp:UpdatePanel ID="UPDHiddenFields" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField ID="HFTest" runat="server" />
<asp:HiddenField ID="HFReturnMessage" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn_force_async" EventName="click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btn_force_async" runat="server" style="display:none;"/>
</div>
</form>
</body>
</html>
webform.aspx.vb // The codebehind
Public Class webform
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
If HFTest.Value = "ok" Then
HFTest.Value = ""
HFReturnMessage.Value = "ok"
Else
HFTest.Value = ""
HFReturnMessage.Value = "error, the HFTest is not ok ! "
End If
UPDHiddenFields.Update() 'Update hidden field panel on client side
End If
End Sub
End Class
Hope this help you.
When I change the selection of my dropdown, the Change event does not fire. I put a breakpoint in the method and the program does not stop.
This is my markup:
<form id="form1" runat="server">
<div style='text-align:center;'>
<a style='text-decoration:none;font-size:16px;color:blue;background-color:white;width:200px;padding:4px;' href='LocationDetails.aspx?Location_ID=0' target='detailPanel'> Add Location
</a></div>
 
<div style='text-align:left;'>
<asp:Label ID="FacilityTypeLbl" runat="server">Facility Type:</asp:Label>
<asp:DropDownList ID="FacilityTypeDDL" runat="server" AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="FacilityTypeDDL_SelectedIndexChanged">
</asp:DropDownList>
</div>
<hr/>
<%ListLocations()%>
</form>
This is my Page_Load method to populate the list and it works fine.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
GetServiceTypes()
FacilityTypeDDL.DataSource = dtServiceTypes
FacilityTypeDDL.DataTextField = dtServiceTypes.Columns("Title").ToString()
FacilityTypeDDL.DataValueField = dtServiceTypes.Columns("ID").ToString()
FacilityTypeDDL.DataBind()
End If
End Sub
This is my change event:
Protected Sub FacilityTypeDDL_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles FacilityTypeDDL.SelectedIndexChanged
strFacilityValue = FacilityTypeDDL.SelectedValue
ListLocations()
End Sub
I put a breakpoint at the first line of code and after changing the dropdown selection it does not stop at this event.
What am I doing wrong?
UPDATE
This is my entire markup. Can there be something wrong this it?
<%# Page Language="VB" AutoEventWireup="true" CodeFile="Locations.aspx.vb" Inherits="Editor_Locations" %>
<!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 id="LocationHead" runat="server">
<title>Locations</title>
<meta http-equiv="Content-Language" content="en-us"/>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
</head>
<body>
<form id="form1" runat="server">
<div style='text-align:left;'>
<asp:Label ID="FacilityTypeLbl" runat="server">Facility Type:</asp:Label>
<asp:DropDownList ID="FacilityTypeDDL" runat="server" AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="FacilityTypeDDL_SelectedIndexChanged">
<asp:ListItem>Test1</asp:ListItem>
<asp:ListItem>test2</asp:ListItem>
<asp:ListItem>Test34</asp:ListItem>
</asp:DropDownList>
</div>
<hr/>
</form>
</body>
</html>
UPDATE
This application is a web site, not a web application. (I didn't know there was a difference but now I do.) In trying to figure out way the SelectedIndexChange event will not fire, I added a button and a click event. When I change the selection in the dropdown list, no event fires. When I click the button, the click event fires, then the selectedindexchange event fires.
I don't think the event SelectedIndexChanged is going to work.
Is there any other way to wire up a Postback when the dropdown list changes?
Can I somehow use __doPostback from a javascript function call when the list changes?
Any suggestions would be greatly appreciated!
I could not get the asp:DropdownList to fire the SelectedIndexChanged event. So this is how I completed the task.
Adding the dropdown dynamically as shown above and adding the change event that calls a javascript:
onchange='UpdateLocationList()'
This function had to be put in a .js file. This web site had a .js file already. It also had some AJAX calls that I used to complete the task.
In the UpdateLocationList(), I get the ID of the service type that was set as a value attribute in the dropdown. Then I use a function that is already part of the .js file to the LocationDetails page using the Service Type ID to display only the facilities of that service type. This is the function:
function updateLocationList() {
var ddlFacilityType = document.getElementById("FacilityTypeDDL");
var facilityValue = ddlFacilityType.options[ddlFacilityType.selectedIndex].value;
processAjax("/editor/Locations.aspx?Location_ID=" + facilityValue, "navPanel");
}
Works like a charm.
Thanks for all of your help.
According to this post you can intercept the post by overriding this function __doPostBack but it wont work. If I view the generated source I am not able to see the function that is meant to be auto generated and causes asp.net to make the postback.
where is this function? and how do I intercept it?
I'm using asp.net 4 and vs 2012
Default.aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
//breaks here as it cant find __doPostBack
var __original = __doPostBack;
__doPostBack = myFunction();
function myFunction() {
alert('intercept');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub form1_Load(sender As Object, e As EventArgs) Handles form1.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim txt As String = TextBox1.Text
End Sub
End Class
An ASP.NET Button renders an <input type="submit" /> to postback the form, and will never use this method. The __doPostBack method is only used for elements that are not input buttons that do not normally cause a POST operation to the server. This is a function that's inside one of the Microsoft's JavaScript file, and only gets rendered out on the client. Common uses for __doPostBack are LinkButton controls, controls that may have AutoPostBack="true", and others.
Also, there may be a call to WebForms_DoPostBack... something named like that that also posts back, but internally calls __doPostBack.
If you are trying to prevent postback on click of your button, attach to the submit event of the form, and cancel the postback operation that way.
I'm trying to have two things happen when I click on a button in an ASP.NET page:
Change the text in an ASP:Label.
Disable the button.
I've done a lot of research on this, but I've had difficulties doing either.
For #1, I thought that this should work, but it doesn't:
<%# Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub BtnSubmit_Click(sender As Object, e As System.EventArgs)
Label1.Text = "Working..."
System.Threading.Thread.Sleep(5000)
Label1.Text = "Done."
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="server" />
<div>
<asp:ListBox runat="server" Height="100px" />
<br />
<asp:UpdatePanel runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnSubmit" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Press the button" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button runat="server" ID="BtnSubmit" OnClick="BtnSubmit_Click" Text="Submit Me!" />
</div>
</form>
</body>
</html>
The "Working..." message is never displayed.
As for #2, I added this to the button (I forget where I found it):
OnClientClick="this.disabled = true; this.value = 'Working...';"
UseSubmitBehavior="false"
That had the desired effect of disabling the button and changing its text (value), but it wasn't possible to change it back using Text and Enabled properties.
I just found a solution on msdn (http://msdn.microsoft.com/en-us/library/bb386518.aspx). Added some code and remove some unnecessary parts.
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void btnDoWork_Click(object sender, EventArgs e)
{
/// do something long lasting
System.Threading.Thread.Sleep(3000);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script language="javascript" type="text/javascript">
<!--
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
var postBackElement;
function InitializeRequest(sender, args) {
if (prm.get_isInAsyncPostBack()) {
args.set_cancel(true);
}
postBackElement = args.get_postBackElement();
if (postBackElement.id == 'btnDoWork') {
$get('btnDoWork').value = 'Working ...';
$get('btnDoWork').disabled = true;
}
}
function EndRequest(sender, args) {
if (postBackElement.id == 'btnDoWork') {
$get('btnDoWork').value = 'Done!';
$get('btnDoWork').disabled = false;
}
}
// -->
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Hello World!"></asp:Label><br />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnDoWork" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnDoWork" runat="server" Text="Start!" OnClick="btnDoWork_Click" />
</div>
</form>
</body>
</html>
What you basically do, is you register some eventHandler for Initialize_ and End_Request - in those you disable and enable your button!
HTH
ASP will not flush the result to the browser while working even if you use an UpdatePanel. It will finish the jobb (including the sleep) before flushing.
You can use a UpdateProgress to show the "Working.." text.
<asp:UpdateProgress>
This will show its content while the UpdatePanel is working. Once the UpdatePanel is finished, the content will disappear.
What you need in you ClickEvent is:
Label1.Text = "Done."
btnSubmit.Enabled = false
This will show the Done text and disable the button. And tell the UpdateProgress to disappear.
The Working message is never displayed because you are executing the script on the server, which doesn't respond to the client until the method exits.
ASP.NET AJAX has a built in control for displaying messages like this while the UpdatePanel is waiting on the server.
Check out the UpdateProgress Control:
<asp:UpdateProgress runat="server" id="progress" ><ProgressTemplate>Working...</ProgressTemplate></asp:UpdateProgress>
You can disable the button by setting the Enabled property to false in your server-side method.
BtnSubmit.Enabled = false
#1: You will never see the message "Working" as you stopped the thread .... Every Message will be shown when your process has "ended".
#2: you coded clientSide to disable the button, there is no code to re-enable your button
hth
First off, "working" never appears because the final value of the label at the time of post-back is "Done." Think about what is happening here - you click the button which causes a post-back to the server. It processes the post-back which includes running the button click code, the result of which is then sent back to the browser. Your 'working' text never makes it back over the wire.
I am not clear on what you're trying to accomplish with the client-side code, but to do what you describe you're almsot there server-side:
Protected Sub BtnSubmit_Click(sender As Object, e As System.EventArgs)
Label1.Text = "Done."
btnSubmit.Enabled = false
End Sub
Also, but your button inside your update panel template tags so it participates in the ajax-postback.
How can I go to an anchor tag on the page when the myDropDownList_SelectedIndexChanged() event fires?
I am using regular ASP.NET Forms.
Update: The following is valid for an ASP.NET Button. I would like to achieve the same functionality (going to #someAnchor) when I select an option from the Dropdown list.
<asp:Button ID="btnSubmit" runat="server" Text="Do IT" Width="186px" PostBackUrl="#myAnchor" CausesValidation="false" />
Update: I will try to further explain details that I didn't cover in enough detail initially.
This is a long page and in the middle of the page there is a dropdown list. Below the dropdown list is a label that will change based on the item selected from the dropdown. The update of the label will occur during the postback. At this point the page needs to remain focused on the dropdown. I tried to use AJAX to accomplish this, but other implementation details prevent that from working. The ability to go to an anchor tag after the postback would be a simple solution. Here is a simplified version of what I am trying to accomplish.
<%# Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub myDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
myLabel.Text = myDropDown.SelectedValue
'When this finishes, go to #myAnchor
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Imagine many lines of text here.
<a name="myAnchor"></a>
<asp:DropDownList ID="myDropDown" runat="server" OnSelectedIndexChanged="myDropDown_SelectedIndexChanged" asdf="asdf" PostBackUrl="#myAnchor"></asp:DropDownList>
<asp:Label ID="myLabel" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
This could do the trick
<asp:DropDownList ID="DropDownList1" runat="server"
onchange="document.location= this.value">
<asp:ListItem Text="Anchor" Value="#anchor"></asp:ListItem>
<asp:ListItem Text="Anchor2" Value="#anchor2"></asp:ListItem>
</asp:DropDownList>
You mention myDropDownList_SelectedIndexChanged() (server code) but you must do it on client side, unless you have a good reason to go to the server
Add this to your page load and you will be good to go.
Page.MaintainScrollPositionOnPostBack = true;
I would use JavaScript--either register the script in your codebehind, or have an asp:Literal which is only visible after the SelectedIndexChanged event. Modify the location.href to append your anchor.
One way to do this is to use the forms.Controls bla bla bla properties in ASP.NET.
however I would suggest you to use a asp.net hyperlink control or link button and this would allow you to access it directly with its ID.
thanks,
MNK.
This requirement has simple javascript solution.But the problem is the design is flawed.Once you move to a new area in screen you cant access the navigation select list without scrolling back.Anyway something like the following works
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!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>
<script type="text/javascript">
function Goto(x) {
window.location = "#"+x.value;
}
</script>
</head>
<body>
<select id="Select1" name="D1" onchange="Goto(this);">
<option value="Loc1" >go to 1 </option>
<option value="Loc2">go to 2 </option>
<option value="Loc3">go to 3 </option>
<option value="Loc4">go to 4 </option>
</select><form id="form1" runat="server">
</form>
<strong> <a href="#" id="Loc1" >Location 1</a></strong>
blah
<strong>Location 2</strong>
<strong>Location 3</strong>
<strong>Location 4</strong>
</body>
</html>
Here is what I have implemented to accomplish my desired result.
Protected Sub myDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myDropDown.SelectedIndexChanged
Response.Redirect("Default.aspx?myDropDown=" & myDropDown.SelectedItem.Text.ToString.Trim & "#myAnchor")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim myDropDownValue As String = Request.QueryString("myDropDown")
If myDropDownValue <> "" Then
myDropDown.Items.FindByText(myDropDownValue).Selected = True
Label1.Text = GetTextBasedOnDropDownSelection(myDropDownValue)
End If
End If
End Sub
If your dropdown list contains three items say for example:
Page1
Page2
Page3
Give the dropdownlist a property of AutoPostBack="true" and then in the dropdown OnSelectedIndexChanged method write the following:
if (DDl.SelectedIndex == 1) {
Response.Redirect("~/page1");
}
else if (DDl.SelectedIndex == 2) {
Response.Redirect("~/page2");
}