Setting a session variable before AutoPostBack fires in an asp:Button - c#

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...

Related

Why label's value is changed?

I know even if the ViewState is disabled for the TextBox, we are not losing the data because it implements the IPostBackDataHandler interface.
<asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"/>
But my question is why this happens for label too? Why label is not losing it's data even if the ViewState is disabled since the label doesn't implements the IPostBackDataHandler interface?
<asp:Label ID="Label1" runat="server" EnableViewState="False" ViewStateMode="Disabled"/>
TextBox definition:
public class TextBox : WebControl, IPostBackDataHandler,
Label definition:
public class Label : WebControl, ITextControl
My code:
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" EnableViewState="False" ViewStateMode="Disabled" Text="Before click"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick"/>
</div>
</form>
And code behind:
protected void Button1_OnClick(object sender, EventArgs e)
{
Label1.Text = "Changed.";
}
I expected to see the "Before click" in my label after I clicked the button but I see the "Changed" text in my label after I clicked the button.
Ok I deleted my previous answer, I will try to re-state it with an example.
First, as others stated, the idea of ViewState is to hold the state between postbacks, rather than during a single page load cycle, so what you're seeing is the expected behavior.
To see the difference with an example, try adding your label with 2 buttons:
<asp:Label ID="Label1" runat="server" EnableViewState="False" Text="Before click"></asp:Label>
<asp:Button ID="btn1" Text="Click" OnClick="btn1_Click" runat="server" />
<asp:Button ID="btnReset" Text="Reset" OnClick="btnReset_Click" runat="server" />
Where btn1 sets the value to "Changed", and btnReset has an empty handler.
Now with EnableViewState set to False, if you click on btn1 the page reloads, btn1_Click is executed, and the page is rendered with the label value = "Changed", if you click btnReset the page will reload again, but since view state is disabled, the label will revert to its original text "Before click"
If you set EnableViewState to True on the lable and click btn1 then btnReset, the label value will stay as "Changed", since the state is kept during postbacks
Hope that clarifies things a bit
This is going to be long and detailed.
Let's start with this markup. Almost identical to yours, with one additional button and a label. I'll explain why we need them later.
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" EnableViewState="False" ViewStateMode="Disabled" Text="Before click"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" EnableViewState="False"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_OnClick"/>
<asp:Label ID="Label2" runat="server" Text="Blah" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_OnClick"/>
</div>
</form>
And we'll use this code behind. Again, I'll explain the purpose of the second handler later on:
protected void Button1_OnClick(object sender, EventArgs e)
{
Label1.Text = "Changed";
}
protected void Button2_OnClick(object sender, EventArgs e)
{
Label2.Text = Label1.Text;
}
Let's see what happens when we initially load the page. First ASP.NET reads all the markup, and then goes through the page life cycle with all the events. In markup parsing stage Label1 gets assigned text Before click, and it is never changed later during initial load. So later during rendering phase this is what is getting rendered into HTML and sent to browser. Thus Before click is displayed on the screen. Nice and easy.
Now we click Button1. Postback occurs, which is a term that describes a request sent to the same page by one of its controls after it was initially loaded. Again, everything starts with ASP.NET parsing the markup, and again Label1 gets assigned text Before click. But then page life cycle events happen, including control event handlers. And in the handler for Button1 the text of Label1 is changed to Changed. Now here is the important thing to note: if ViewState for the Label1 was enabled, this new value would be stored in there, and so called tracking would be enabled for property Label1.Text. But ViewState is disabled, and so the new value is not stored anywhere except Label1. Next comes the rendering page stage, and since Label1.Text still holds the value Changed this is what is rendered into HTML and sent to the browser to display. Note however that this new value is not sent inside the ViewState field. As you can see, whether ViewState is enabled or not plays no role in what is displayed after this postback.
Now we'll click Button2, which would trigger another postback. Again, ASP.NET parses the markup, again Label1 gets text Before click. Then comes ViewState loading part. If ViewState for Label1.Text was enabled, it would load changed value into this property. But ViewState is disabled, and so the value stays the same. Thus, when we reach Button2 click handler, the value of Label1.Text is still Before click, which is assigned to Label2.Text. But Label2 has ViewState enabled, and so this new value for its text is stored in ViewState and sent to the client (ViewState is implemented as a hidden field on the client side). When everything gets to the browser, we can see Label1 and Label2 both displaying Before click.
And to nail it down we'll do a third postback, now clicking Button1 again. Just as during the first postback, Label1 ends up with Changed text. But what about Label2? Well, this one has ViewState enabled, so during initial markup parsing ASP.NET assigns it the value Blah, and during ViewState loading it replaces this value with Before click. Nothing else affects this value during the page life cycle (we did not click Button2 this time), and so we end up seeing Changed and Before click in the browser.
Hopefully it makes it clear what the ViewState is for and what disabling it does. If you want to dive even deeper into how ViewState works, I would greatly recommend this article: TRULY Understanding ViewState.
I think you have wrong understanding what ViewState is.
Data in ViewState is being stored BETWEEN requests, but not DURING page lifecycle.
BTW - ViewState data is generated after PreRenderComplete event in SaveStateComplete event.
https://msdn.microsoft.com/en-us/library/ms178472.aspx
If you have ViewState switched off - just think that it will not be generated in output.
During page lifecycle all data assigned to controls(and also to page fields and properties, as the page is just a class) will be rendered as you defined in aspx. But will be lost after, unless is saved in ViewState.

How to implement a click event on textbox in ASP.NET?

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.

Is this the intended behavior of textbox and label?

I set the value of the controls when the DOM loads. I have this super simple code on aspx page:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=textBox2.ClientID %>').val($('#<%=textBox1.ClientID %>').val());
$('#<%=lblVal.ClientID %>').html($('#<%=textBox1.ClientID %>').val());
});
</script>
<asp:TextBox runat="server" ID="textBox1" Text="Test data" />
<asp:TextBox runat="server" ID="textBox2" />
<asp:Label runat="server" ID="lblVal" Text="Old Data" />
<asp:Button runat="server" Text="Click Me" onclick="Unnamed1_Click" />
In my button click event handler I have this code:
protected void Unnamed1_Click(object sender, EventArgs e)
{
Debug.Write(textBox2.Text);
Debug.Write(lblVal.Text);
}
The thing that came shocking to me lblVal has it's old value. Setting value in javascript doesn't really have any effect on label whereas the textbox2's data is reflected on the server. Is the intended behavior of textbox and label? This came as a bit of surprise to me because I never came across this thing previously.
The label will get rendered to an HTML label tag, not a form field. Therefore it does not have a value that is posted when the form is submitted, and the value you get restored in the postback is from ViewState. Form fields (e.g. a ASP TextBox which becomes an input) will post their value and this will override the value in viewstate.
You could get around this by instead having a hidden input which you update with javascript, and then in your postback update the label with the contents of that instead.
An asp:Label control renders to a span, and is therefore not a form element, and its changed contents will not be posted to the server.

Triggering a postback from Javascript fails

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 %>', '');
}
}

Setting focus on top of the page on click of asp.net link button

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;
});

Categories