C# List<LinkButton> Collection cssclass not getting applied - c#

I've couple of LinkButtons for which I want to manipulate the cssclass property.
Earlier I used each LinkButton individually to change the cssclass and it worked perfectly upon postback. E.g. lnkbtnHome.CssClass = "tab";
But over time the items increased so I thought it could be better way to do it and I decided to use the Listcollection and use foreach loop to do the same.
Below is the code that I'm using currently.
By default (upon page load) the first button is having a different class tabsel and I want to reset the class of all buttons by setting the class to tab. Upon debugging I can see the cssclass getting modified but it's not changing up in the browser.
Am I missing something?
Under Declaration:
static List<LinkButton> lnklist;
Under PageLoad:
lnklist = new List<LinkButton>();
lnklist.Add(lnkbtnHome);
lnklist.Add(lnkbtnSubject);
lnklist.Add(lnkbtnReport);
Upon Postback:
foreach (var lnkbtn in lnklist){
lnkbtn.CssClass = "tab";
}

Never use static fields in ASP.NET!
You:
I used static to avoid losing the items upon postback.
but that's the nature of HTTP. It's a stateless protocol. You should recreate all controls on each postback in the same way as ASP.NET does it. Otherwise you're are vulnerable to various issues since ASP.NET is a multithreading environment. You could store it in the Session, but i would advise against it. LinkButton is a webcontrol which needs to be part of the current page's control collection. This page will be destroyed at the end of it's lifecycle.

Related

Viewstate value erased when using Control

A little new to asp.net.
In my main.aspx page i have:
<users:UsersControl runat="server" ID="usersControl" />
In my UserControl page_load i have:
ViewState["test"] = "test";
In my Page_PreRender in main.aspx.cs:
log...(ViewState["test"]); <-- empty
Why dont i see the value on test?
Im guessing here that the ViewState collection is different in the two contexts you have mentioned.
The first is in the context of the control, and the second is in the context of the page, therefore "test" key is not shared between them.
Also, it is not a good idea to expose a controls ViewState beyond the control boundary. For example use properties on the UserControl as the interface to the viewstate, e.g
public string Test
{
get { return this.ViewState["Test"]; }
set { this.ViewState["Test"] = value; }
}
ViewState should be considered an internal implementation detail of the user control.
Then whenever you need to use this property from the page:
this.userControl1.Test = "This Goes Into ViewState";
I've found a similar answer to your question:
.net ViewState in page lifecycle
It's necessary to understand the life cycle, so why don't use Attributes on the UserControl?

How to save property of Code behind page in ASP.NET 4.0 (not use static)?

Now I have a change to build a web application in asp.net. The style of ASP.net brings me some weird. The hardest problem is that I couldn't save the value of variable after each PostBack event (when we click button). I've see one solution in the question Dynamic User Controls get and maintain values after postbacks but it just only familiar with the value which binding with controls.
Now I think about 2 solutions:
Like the reference question above, I’ll unbind the data when the page PostBack. I’ll save a variable in a Session and in the UnBind method, I’ll reload to variable in session.
Use the ajax Button (not reload all pages): I really want to use this method, but it sounds very easy to be error. I feel very hard to use Ajax control in asp.net.
My code:
public class MainPage
{
//variable
private List<string> lstName;
public MainPage()
{
if (!IsPostBack)
{
lstName = new List<string>();
}
}
}
Now I found a method to save property of Code Behind Page in ASP.NET 4.0.
That's use ViewState["variableName"] variable. When I need to save a property (e.x var ttsHandler), I save it: ViewState["ttsHandler"]=ttsHandler;
When I need to load its value, I have to type casting:
ttsHandler=(TTSHandler) ViewState["ttsHandler"];
But this solution still only useful with well-known Class type (string, int...) because it have to be Serializable. Unfortunately, some property I can't assign its Class Serializable.
Ex: I have to assign a MyThread class (subclass of System.Thread.Threading), and the debugger require project to Serializa System.Thread.Threading class, that's impossible.
Now I have to use another method, that's not so good, is using Session["var"] instead of ViewState. I'll try my best to handle this, and I'm very glad with your help.

Problems when assigning values via JavaScript to Asp.net labels and then passing via C# session object

I am assigning variables to asp labels via javascript with a simple innerHTML call
example:
document.getElementById('labelName').innerHTML = parseFloat(var).toFixed(2);
It appears in the label fine, and I am able to continue to manipulate it via javascript.
I then set it up so that that variable is put into a session object via C# codebehind buttonClick event.
example:
protected void btnConfirm_Click ( object sender, EventArgs e )
{
Session["sessionName"] = labelName.Text;
}
The buttonConfirm_Click method fires it Response.Redirects to another page and populates asp labels with the session object via the c# codebehind page_load method.
example:
lblResult.Text = Session["sessionName"].ToString();
When doing this, the label is empty, no errors or 'null'. I have tried to narrow down the issue by trying various things. When I assign the text explicitly in the c# code behind of the first page and the recieve and assign it to the label on the next page, it shows correctly.
example:
Page 1:
Session["sessionName"].ToString() = "Test";
Page 2:
lblResult.Test = Session["sessionResult"].ToString();
I have tried several other things, such as casting the variables in javascript and in the codebehind, and checking to make sure I had runat="server" within each applicable label.
Anyways, is there something here I am missing? Is asp.net unable to detect the changes that javascript has made to the labels? Are there some incompatibility issues when using innerHTML or anything like this that maybe be causing such a thing to occur?
Thanks in advance!
The problem is that the text in a span tag (that is what asp:Label will render) isn't sent in the post to the server and therefore you can't read your changes server side. You'll need to use a input element (hidden field, textbox etc depending on what your ui should look like).

Prevent duplicate postback in ASP.Net (C#)

Simple one here... is there a clean way of preventing a user from double-clicking a button in a web form and thus causing duplicate events to fire?
If I had a comment form for example and the user types in "this is my comment" and clicks submit, the comment is shown below... however if they double-click, triple-click or just go nuts on the keyboard they can cause multiple versions to be posted.
Client-side I could quite easily disable the button onclick - but I prefer server-side solutions to things like this :)
Is there a postback timeout per viewstate that can be set for example?
Thanks
I dont think that you should be loading the server for trivial tasks like these. You could try some thing jquery UI blocking solution like this one. Microsoft Ajax toolkit should also have some control which does the same. I had used it a long time ago, cant seem to recall the control name though.
With jQuery you can make use of the one event.
Another interesting read is this: Build Your ASP.NET Pages on a Richer Bedrock.
Set a session variable when the user enters the page like Session["FormXYZSubmitted"]=false.
When the form is submitted check that variable like
if((bool) Session["FormXYZSubmitted"] == false) {
// save to db
Session["FormXYZSubmitted"] = true;
}
Client side can be tricky if you are using Asp.Net validation.
If you have a master page, put this in the master page:
void IterateThroughControls(Control parent)
{
foreach (Control SelectedButton in parent.Controls)
{
if (SelectedButton is Button)
{
((Button)SelectedButton).Attributes.Add("onclick", " this.disabled = true; " + Page.ClientScript.GetPostBackEventReference(((Button)SelectedButton), null) + ";");
}
if (SelectedButton.Controls.Count > 0)
{
IterateThroughControls(SelectedButton);
}
}
}
Then add this to the master page Page_Load:
IterateThroughControls(this);
I have had the same scenario. The solution of one of my coworkers was to implement a kind of Timer in Javascript, to avoid considering the second click as a click.
Hope that helps,
Disable the button on click, utilize jquery or microsoft ajax toolkit.
Depending on how important this is to you, could create an array of one time GUID's which you remove from the array once the update has been processed (ie posted back in viewstate/hidden field)
If the guid is not in the array on postback, the request is invalid.
Substitute database table for array in a clustered environment.

user control event handler lost on postback

I have a menu usercontrol called LeftMenu that has a bulletedlist of linkitems. It's on the ascx page as such:
<asp:BulletedList ID="PublisherList" DisplayMode="LinkButton" OnClick="PublisherList_Click" cssClass="Menu" runat="server"></asp:BulletedList>
I databind the list in the page_load under if(!isPostBack)
I'm having an issue on a page that loads the control. When the page first loads, the event handler fires. However, when the page posts back it no longer fires and in IE8, when I'm debugging, I get "Microsoft JScript runtime error: Object expected" in Visual Studio pointing at "__doPostBack('LeftMenu$PublisherList','0')." In FF I don't get the error, but nothing happens. I'm not loading the control dynamically, it's loaded on the aspx page using:
<%# Register TagPrefix="Standards" TagName="LeftMenu" Src="LeftMenu.ascx" %>
<Standards:LeftMenu ID="LeftMenu" runat="server"/>
Any ideas of where I'm losing the event handler?
I just realized this is happening on another user control I have as well. A text box and a button and I'm using the default button to make sure pressing the enter key uses that button. .Net converts that in the html to:
<div id="SearchBarInclude_SearchBar" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'SearchBarInclude_QuickSearchButton')">
so as soon as i enter a key in the box I get a javascript error at the line saying "object expected." It seems like the two issues are related.
Edit Again: I think I need to clarify. It's not that I'm clicking on the menu item and it can't find the selected item on postback. I have this search page with the left navigation on it and then the main content of the page is something that causes a postback. Everything is fine with this postback. Once that page has been posted back, now if I click on the bulleted list in the left navigation I get a javascript error and it fails. The page_init for the LeftMenu control is never called.
It sounds like you might be losing the click because you are not DataBinding the list on PostBack. Therefore, the post back is trying to refer to a control (a specific bulleted list item) that does not exist.
You should try binding the list again on PostBack just to see if that fixes your issue. BUT, what should REALLY happen is that the LeftMenu and the BulletedList should store their information into ViewState so that you can ensure that the data that was shown to the user on their initial page load is the same data that the PostBack is processing and working with.
If you have EnableViewState=true for your UserControl and all controls within it, everything should work fine. With ViewState enabled, ASP will reinflate your controls from ViewState after Init has fired. This means that the postback event arg (which points to an index in your control list) will still find the control in that list position. Otherwise the list is empty on postback.
However, ViewState is the work of the devil and was designed simply to foster the illusion that you are working in a stateful environment. It is okay to use it for small amounts of data but typically not advisable for templated controls like repeaters and lists because you have no idea how much data is going to be created in ViewState.
If you are dealing with static, or relatively static data, store it in the application cache and rebind your lists in Page.Init every time (note that it has to be in Init because post-init is when ASP rebinds from ViewState; if you get in there first, your data will be used instead).
If you are dealing with volatile data, you have a problem because the data you rebind must be exactly the same as the original page request, otherwise the postback events will be firing against the wrong rows. In that case you need to either store your initial data in Session or you simply store the list of rows ids (in a hidden variable or Session) and you recreate the data to bind against from the ids each time.
An even better solution is to not use postback events at all. Try to turn all your events into GETs that have an ID on the query string. You can still create the list using binding the first time through the page (as you are currently doing), and you can even GET the same page with a new ID.
If you need to keep state on the same page but need to respond to the user changing a radio button selection (or something else), think about using Ajax calls to update the screen. You also do that with an ID that you pass to the Ajax call.
In general, the more you move from using stateful ASP, the lighter and more responsive your pages will become. You will also be in a better position to move to stateless MVC if necessary. You will also save lots of time lost to debugging obscure problems because ViewState is not available when you need it to be.
The best analysis of ViewState I've read is in the link below. If you fully understand how it works, you can continue to use it without necessarily incurring the costs.
http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx
It's possible that this might be javascript related, and that a script that is loading earlier in the page is throwing an error and causing the page to not be loaded properly.
Are your usercontrols loading any javascript onto the page? Can you check for javascript errors on the initial load of the page?
I moved the code into an existing project we have and for some strange reason, I stopped getting the javascript errors and instead got:
"Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
I haven't quite figured out where I'm supposed to put the register event validation with a user control, but in the mean time I just set enableeventvalidation=false and it seems to work now.
It looks like the doPostBack function is missing since its arguments are literals so they couldn't be the cause. Is that one of your own functions or did you mean to call the ASP __doPostBack function?
Have a look at the Firefox error console or allow script debugging in IE and see exactly what object can't be found. Even better, download Firebug and debug it.
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.

Categories