I am trying to trigger a postback if a certain condition is true. Initially, a user will click on a button on my form, the server does some work, and in the process of doing that work it assigns a hidden field the value of '1'. When the page reloads after that very first postback, I am trying to use javascript to check the hidden field, and if it is '1' I need the page to postback again so the server side can do some additional processing. The reason for doing it this roundabout way is so that I can create controls on the form from my C# code behind as well as download a file in 1 user interaction. Here is what I have so far:
<script type="text/javascript" language="JavaScript">
function atload() {
var HWInfo = document.getElementById('HiddenHW').value;
if (HWInfo == '1') {
alert("flag has been set");
__doPostBack('<%= hdnHidden.UniqueID %>', '');
}
}
$(document).ready(atload);
</script>
The alert that says the flag has been set correctly fires, but the __doPostBack does not. In my ASPX file, here is the relevant part:
<form id="InventoryForm" runat="server">
<div>
<asp:Label ID="lblClientList" runat="server" Text="Client List"></asp:Label>
<asp:DropDownList ID="comboClientList" runat="server"></asp:DropDownList>
<asp:Label ID="spacer1" runat="server" Text=" "></asp:Label>
<asp:Button ID="btnGenerateHWReport" runat="server" Text="Generate Hardware Inventory Report" />
<asp:Label ID="spacer2" runat="server" Text=" "></asp:Label>
<asp:Button ID="btnGenerateSWReport" runat="server" Text="Generate Software Inventory Report" />
<br />
<br />
<asp:Panel ID="MissingCompPanel" runat="server"></asp:Panel>
<asp:HiddenField ID="HiddenHW" runat="server" Value="0" />
<asp:HiddenField ID="hdnHidden" runat="server" />
</div>
</form>
I can tell the postback never fires, because I have breakpoints in the Page_Load C# codebehind that never get tripped. I have break points on almost every single line of this:
if (!Page.IsPostBack)
{
// Page is not a postback, this is the first visit here
string foo = HiddenHW.Value;
}
else
{
// Page is a postback and not initial load
string foo = HiddenHW.Value;
}
Why is my __doPostBak after the alert not firing, and is there a better way to do this? The end result I want is if my hidden field is '1', then I want my 2nd trip to the server to 1) actually happen and 2) know that the hidden field is '1' and not its default '0'.
Thanks!
how about just clicking the submit button programatically and have it call __doPostBack the way it normally does?
Try invoking the __doPostBack method on the page instead of the hidden control
__doPostBack('__Page', '');
When you get the value of HiddenHW, you're not using the right ID. If you look at the rendered source, the ID of the control is something like ctl00_HiddenHW. To get that ID, you should use HiddenHW.ClientID. I believe __doPostBack also needs the ClientID, not UniqueID.
function atload() {
var HWInfo = document.getElementById('<%= HiddenHW.ClientID %>').value;
if (HWInfo == '1') {
alert("flag has been set");
__doPostBack('<%= hdnHidden.ClientID %>', '');
}
}
Related
In my web application I need a functionality so that when users click on textbox to input values, it should make the button and the other fields visible?
I am using the code provided below but, could not get it working.
C#:
protected void TextBox1_Click(object sender, EventArgs e)
{
ButtonSearch.Visible = true;
}
ASP.NET:
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" Visible="False" />
How to accomplish this?
Set AutoPostback="True". This way the event will be fired server-side, and the button will become visible.
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" OnClick="TextBox1_Click" AutoPostBack="true"></asp:TextBox>
However, if you only want to toogle visility of a button, you really should considerate javascript. This will save a trip back to the server.
<asp:TextBox onclick="txtBox1_ClientClicked()" ID="TextBox1" runat="server" OnClick="TextBox1_Click"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" OnClick="ButtonSearch_Click" Text="Search" style="display:none;" />
<script type="text/javascript">
function txtBox1_ClientClicked(){
var theButton = document.getElementById('<%=ButtonSearch.ClientID%>');
theButton.style.display = 'block';
}
</script>
You do not need to post back to the server to accomplish your job. You can use client side onFocus event and javascript/jquery, for example.
I know I used an input of type text, and you are using an ASP Control which posts on server, but here is a JSFiddle to get you on the right track: http://jsfiddle.net/Mmjtz/1/
$("<%= ButtonSearch.ClientID %>").click(function(){
$("#TextBox1").show():
});
In this code you need to pass fields ID which you want to visible on the click of button.
Put the textbox inside a div and use the div's onClick event from codebehind. It's not what you asked but it works for me without any errors. Here is a javascript function to implement requested event:
function toggleVisibility()
{
document.getElementById('TextBox1').disabled = true;
/*
...some other code...
*/
}
And of course, you have to define your onclick event at the div definition after implementing this JS function.
<div id="TBdiv" onClick="toggleVisibility()">
<asp:TextBox ID="TextBox1"..../>
</div>
IMPORTANT: Since you now disabled your TextBox from codebehind, you have to enable it in somewhere before you want to use it again. Otherwise you will not see it while the page is running.
jQuery is the perfect solution for your problem. The code would be something like this:
$("#TextBox1").on("click",function(){$("#ButtonSearch").css("visibility", "visible");})
You include the script by adding <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> to the page and then you can add the piece of code above to within <script></script> tags.
I was wondering if you guys could help me understand hidden fields, since I don't think I am getting them to work.
On the aspx page I have:
<asp:HiddenField ID="hidVal" value="" runat="server" />
On a button click I have a JavaScript function called
<button type="button" id="search" onclientclick="search_click()">Search</button>
With the function being
function search_click() {
document.getElementById('hidVal').Value = "1";
<% save(); %>
}
In aspx.cs I have a function that does this:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
After clicking the button I look into the file and there is no change.
Is my approach correct or am I not understanding how this works?
Putting <% save(); %> in a JavaScript function in an aspx page causes save to be run when the page is built on the server, not when the surrounding JavaScript function is called on the client. At this point, the hidden field is empty, so your file gets a blank line written to it. When the user clicks the button, the hidden field is filled, but there's nothing to tell the server that this has happened.
What you need to do instead is something like:
// In your aspx, for the javascript function: remove the call to save,
// use the correct ID for the hidden field
function search_click() {
document.getElementById('<%= hidVal.ClientID %>').Value = "1";
}
// In your aspx in place of the button put
<asp:Button id="search" runat="server"
onclientclick="search_click(); return true;" onclick="search_click">
Search
</asp:Button>
// This results in a button that calls the javascript function on click, and
// then posts back to the server saying that the button has been clicked
// In your C#, this function gets called when the client posts back to
// say that the button has been clicked.
public protected void search_click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(
#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
}
You'll need to reference the client ID of the hidden field, which is probably not hidVal, as the actual client side ID generated in the HTML will be based on the parent control's naming container. There's two ways to fix this. First, you could make the client ID static on the control (which basically tells ASP.NET make the ID exactly what I said.):
<asp:HiddenField ID="hidVal" value="" ClientIDMode="Static" runat="server" />
Second, you can look up the ClientID property from the server when you generate your JavaScript:
document.getElementById('<%= hidVal.ClientID %>').Value = "1";
This would render out the actual client ID directly in the JavaScript code. Either approach is probably fine, but the second one would only work if the JavaScript is embedded directly in your ASPX file and not in a static .JS file.
Calling server side methods:
The second part of your question is about calling server side code when the button is pressed. You should do this by attaching an OnClick handler to your button:
<button runat="server" id="BtnSearch" onclientclick="search_click()" OnClick="btnSearch_Click">Search</button>
When the button is pressed, the page will be posted back and the btnSearch_Click event handler will be called. You'll then be able to handle any server side logic, as well as check the value of your hidden field. Hope this helps!
What you're trying to do is execute a server side function (save) via a client side call. This won't work as it is calling save() when the page first loads and then putting the return value (which is probably nothing) into the code where you put
<% save(); %>
Instead you need your button to fire the save function, but fire your javascript first. You do this by creating an asp:button (which renders as ) and then adding both an "OnClientClick" (for your javascript) and "OnClick" (for your server side function).
<asp:Button id="btnSearch" runat="server" OnClick="btnSearch_Click" OnClientClick="search_click()" text="Search" />
Then in your C# code you need the method to be named the same as the OnClick value:
protected void btnSearch_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
}
The easiest way to create your server side function is to double click on the button in design view, as it will add the correct method call for you.
Hope this helps.
You can change hidden field value in both serverside and client side events.
Change value in client side
<script type="text/javascript">
function setvalue() {
document.getElementById('hidVal').value = "1";
}
</script>
<div>
<asp:HiddenField ID="hidVal" value="" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="setvalue();" />
</div>
Change value in serverside
<div>
<asp:HiddenField ID="hidVal" value="" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
protected void Button1_Click(object sender, EventArgs e)
{
hidVal.Value = "1";
}
How would I go about setting a session variable from the click of an ASP:Button before an AutoPostBack event fires.
Here is what I have right now, but I'm not exactly sure I'm doing this right:
<asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx"
onclick="CommitBTN_Click" UseSubmitBehavior="true"
OnClientClick='<% string temp1 = "true"; Session["ClickedFlag"] = temp1; %>' Text="Commit Changes to Database" />
Would this be the correct way of performing this action or am I going at it completely wrong?
EDIT:
Changed my button tag to this:
<asp:Button ID="CommitBTN" runat="server" PostBackUrl="~/MMR_Home.aspx"
onclick="CommitBTN_Click" OnClientClick="document.getElementById('<%= Hidden.ClientID
%>').value='1'" UseSubmitBehavior="true" Text="Commit Changes to Database" />
I receive this as my error:
Microsoft JScript runtime error: Unable to set value of the property 'value': object is null or undefined
Use this:
Inside aspx file:
<form runat="server">
<asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="document.getElementById('HiddenField').value='Ram'"/>
<asp:HiddenField ID="HiddenField" runat="server" />
</form>
Or
<script type="text/javascript">
function setMyHiddenField(myValue) {
document.getElementById('HiddenField').value = myValue;
}
</script>
<form runat="server">
<asp:Button ID="CommitBTN" runat="server" Text="Button" onclick="CommitBTN_Click" OnClientClick="setMyHiddenField('Ram')"/>
<asp:HiddenField ID="HiddenField" runat="server" />
==================================================================
Inside aspx.cs file
protected void CommitBTN_Click(object sender, EventArgs e)
{
Session["ClickedFlag"] = HiddenField.Value;
Response.Write(Session["ClickedFlag"]);
}
It is easy to replase "Ram" with your value. ;)
you can change Ram to temp1 easy:
setMyHiddenField('temp1')
Or you can call this function on your another control events befor CommitBTN pressed
Use a Hidden Field control.
Update the Hidden Field to 1 on Button Client Click.
Update the Session Value in the Page Load' event. The Value will be 1 then update the Session variable and set theHidden Fieldvalue to 0 underneath theSession Variable` Update.
Reason for the Usage of Page Load event is that on clicking the Button as per the page life cycle the page events like PreInit, Init, InitComplete, PreLoad, Load executes before the execution of Button Control.
Page events execution takes place like below..
Preinit
Init
InitComplete
PreLoad
Load
Control Event
Load Complete
Pre Render
Hope this will help you...
In my ASP.NET main page I have one hidden field and and one button. When the user clicks the button I am showing the pop up (child page). I need to access a Hidden field while the pop up is loading. How could I access the Hidden field using c#?
Well, you can pass the value of the hidden field to the query string of the pop up. Something like this:
<asp:button id="ButtonInMainPage" runat="server" onclick="Popup();return false;" />
<asp:hidden id="hiddenValue" runat="server" />
<script type="text/javascript">
function Popup()
{
window.open('Child.aspx?hiddenValue='+document.getElementById('<%=hiddenValue.ClientID%>').value);
}
In child page_load:
string hiddenValue = Request.QueryString["hiddenValue"];
What I show is simple code, you must add necessary check or other according to your project.
This is your question:
In main page, there is a gridview, which contains a checkbox column, when a checkbox of a row is selected, add the corresponding ID to a hidden field. When user clicks the popup button, a window will be opened and the selected IDs will be passed to the new window. The question is the IDs are too long to pass in the query string.
My solution:
I think you can remove the hidden field, and remove all client scripts of your popup button.
<asp:button id="PopupButton" runat="server" Text="Click to pop up" />
Add a server event of the button, like:
void PopupButton_Onclick(object sender, EventArgs e)
{
string IDs = CollectTheSelectedIDsInTheGridView();
Session["IDs"] = IDs;
string js = #"<script type='text/javascript'>
window.open('Child.aspx');
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(),"showChild",js);
}
EDIT
Your data list must look like this:
<table>
<asp:Repeater ID="myData" runat="server">
<ItemTemplate>
<tr>
<td><asp:CheckBox ID="selectedFlag" runat="server" Checked=<%# Eval("Checked") %> /></td>
<td><asp:Label ID="dataText" runat="server" Text=<%# Eval("TextData") %>></asp:Label></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
I've a asp.net datagrid which shows customer order details.
Pagination at the bottom of the grid is done using datalist and asp.net Linkbutton controls.
Here is the code:
<asp:DataList ID="DataList2" runat="server" CellPadding="1" CellSpacing="1"
OnItemCommand="DataList2_ItemCommand"
OnItemDataBound="DataList2_ItemDataBound" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPaging" runat="server"
CommandArgument='<%# Eval("PageIndex") %>'
CommandName="lnkbtnPaging"
Text='<%# Eval("PageText") %>' />
<asp:Label runat="server" ID="lblPageSeparator" Text=" | " name=></asp:Label>
</ItemTemplate>
</asp:DataList>
When the user clicks on any page number(ie.Link button), I need to set focus on top of the page.
How do i do this?
Thanks!
I think the default behaviour would be for the page scroll position to be set back to the top of the page. Is there anything else in your page that might be overriding this behaviour?
For example:
Is your DataList inside an UpdatePanel? In that case the current scroll position will be maintained over a (partial) post-back. You would therefore need to reset the scroll position to the top of the page yourself. One way to do this would be to implement a handler for the PageRequestManager's EndRequest client-side event which would set the scroll position - this thread explains how
Is the Page MaintainScrollPositionOnPostBack property set to true?
You could try setting a named anchor at the top of the page. Here is an article that explains it http://www.w3schools.com/HTML/html_links.asp
After an AJAX partial postback you may need to return to the top of your ASPX page to display an error message, etc. Here is one way that I have done it. You can add the JavaScript function below to your ASPX page and then call the method when needed in your code-behind by using the ScriptManager.RegisterClientScriptBlock method.
ASP.NET C# Code-behind:
ScriptManager.RegisterClientScriptBlock(this, Page.GetType(),
"ToTheTop", "ToTopOfPage();", true);
JavaScript:
<script type="text/javascript">
function ToTopOfPage(sender, args) {
setTimeout("window.scrollTo(0, 0)", 0);
}
You can also just JavaScript to scroll to the top of the page by using the OnClientClick property of your button. But this will cause this behavior to occur every time the button is clicked and not just when you want it to happen. For example:
<asp:Button id="bntTest" runat="server"
Text="Test" OnClick="btn_Test" OnClientClick="javascript:window.scrollTo(0,0);" />
<asp:LinkButton ID="lbGonder" runat="server" CssClass="IK-get" ValidationGroup="ik" OnClick="lbGonder_Click" OnClientClick="ddd();" title="Gönder">Gönder</asp:LinkButton>`
<script type="text/javascript">
var ddd = (function () {
$('body,html').animate({
scrollTop: 300
}, 1453);
return false;
});