EnableViewState for html tag - c#

I am quite new and I will like to ask a question. Please see the html and codebehind.
HTML
<ul id="menu" runat="server" EnableViewState="True"></ul>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var liItem = new HtmlGenericControl("li");
var aItem = new HtmlGenericControl("a");
liItem.Attributes.Add("class", "test");
aItem.Attributes.Add("href", "#");
aItem.InnerText = "please work";
liItem.Controls.Add(aItem);
menu.Controls.Add(liItem);
}
}
Once postback, the UL data is lost though I have enabled the viewstate. I remember it works last time but now it is not. Anybody can advise? Thanks a lot

This happens because you are dynamically adding data via your first load (!IsPostback), and thereafter (when Page_Load runs again) the data is being lost. You have to keep in mind that EnableViewState is a ASP.NET specific property, So it will only work on server controls inheriting from System.Web.UI.Control
The only way you can achieve this is by either creating your html tags on each and every page load (i.e remove your !IsPostBack check)
or adding a ASP.NET control to the page which supports ViewState (Gridview, ListView, Label, Button etc).

Related

SelectedValue & SelectedItem From Drop Down List

I am attempting to write the selected values to two separate text boxes named this.txtTextSelected.Text = text; and this.txtValueSelected.Text = value;
My issue is that the values are not written to the two text boxes, and when an option is selected my page refreshes and doesn't actually store the selected value which makes me think
1) Either my HTML for the drop down list is incorrect
2) I have added un-needed syntax for something
But I am scratching my head as to what the real deal is.
This is my HTML for the drop down list
<asp:DropDownList ID="dropdownlist1" CssClass="DropDownLists"
runat="server" Width="90px"
AutoPostBack="true"
OnSelectedIndexChanged="dropdownlist1_SelectedIndexChanged">
</asp:DropDownList>
And this is my C# code behind for the page
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = dropdownlist1.SelectedValue;
string text = dropdownlist1.SelectedItem.Text;
this.txtValueSelected.Text = value;
this.txtTextSelected.Text = text;
}
EDIT
Will this remedy my problem (basing this off #David comment below)
if (!IsPostBack)
{
BindDropDownList();
}
(In response to comments and the question edit...)
Unlike WinForms, WebForms "form" objects don't persist in memory. Web applications are designed to be inherently stateless. So every request results in re-instantiating the targeted form object, which invokes all of the start-up stuff that happens in a form.
This includes Page_Load.
So any time you click a button or do anything that involves posting the page back to the server, Page_Load (and other initialization events) happen again, before any event handlers or custom logic.
This means that if you're binding your controls in Page_Load, you're going to re-bind them before you try to use them. In WebForms, the standard fix for this is to wrap them in a conditional when binding:
if (!IsPostBack)
{
// bind your controls
}
This will bind the controls when initially loading a page, but not when re-submitting the page's form to the page (posting back).

ASP.NET : my html element repeated after my postback finish

i have an asp web page and my page contains to RadCombobox. for first drop down i set item_requested method (when the user click on it and select the theater name.it has a post back and after post back the second drop down fill with sans numbers ).
my problem is here:
after page post back the second field set duplicate in my page. in these pictures you can see that.
Before post back:
the second image :(After postback the second fielset repeated)
Note:
all of my controls in update panel. after i remove update panel from my page i doesn't happen again.Do you know the reason ? :[
You probably have some logic where you are adding this component. Try to check IsPostBack before adding the component to the page. Just like that:
if (!IsPostBack)
{
//dynamically add component
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
// ASPX C#
}
}
ASP
................... IM NOT GOOD AT ASP

DropDownList not posting back, even with AutoPostBack set

Obscure solution at end of post
Using asp.net page with C# codebehind, I have successfully built and populated a DropDownList.
What I would like to do is capture a new value selected from the dropdownlist (preferrably using a postback to my codebehind). The codebehind can then update other things on the page based on this newly selected dropdownlist value.
My first attempt was to use
<asp:DropDownList ID="myDDL" runat="server" AutoPostBack="true" OnSelectedIndexChanged="foo"></asp:DropDownList>
with the C# method
public void foo(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
string myValue = "";
if (ddl != null)
{
myValue = ddl.SelectedValue;
// Do some stuff
}
}
This did not work. When the selected index was changed, it simply reloaded the page, but the IsPostBack flag was always false.
So I sifted through SO and tried a number of different tactics. Most recently, I tried to register the client-side onChange event in the codebehind and turned off the AutoPostBack.
in the ASP.Net page:
<asp:DropDownList ID="myDDL" runat="server" AutoPostBack="false"></asp:DropDownList>
in the codebehind:
myDDL.Attributes.Add("onChange", "doSomeStuff(this);"); // Done on databind.
I added the client-side javascript to call the page's __doPostBack function
<script language="javascript" type="text/javascript">
function doSomeStuff(ddl) {
var ddlVals = document.getElementById(ddl.id);
__doPostBack(ddlVals, '');
}
</script>
This also failed, although I thought it was going somewhere when I saw the javascript execute properly.
Looking in the codebehind, though, it's still not working. When I put a breakpoint in the Page_Load IsPostBack is false! But it's supposed to be a postback!? It was posted back using __doPostBack and (seperately) automatically with AutoPostBack="true"
So I dug deeper.
According to this MSDN article (http://msdn.microsoft.com/en-us/library/ms178141(v=VS.85).aspx) based on the results on the page load I'm doing a "Server Transfer" rather than the desired Postback (IsPostBack is false, PreviousPage is, as expected, the same page that should be posting back, IsCallback is false, and IsCrossPagePosting is false).
What could be going on to hyjack the AutoPostBack and the __doPostBack to make it look and act like a "Server Transfer"?
What can I set/check on the parent control/page to make sure it's allowing postbacks?
EDIT:
The Page_Load looks something like:
private SpecialDataObject _someData;
private string foobar;
public void Page_Load(object sender, EventArgs e)
{
//set some variables.
this.foobar = "blah";
LoadSomeUnrelatedData();
if (!IsPostBack)
{
if (_someData == null)
{
LoadDataWithoutBinding();
}
BindMyData();
}
}
With a breakpoint at //set some variables the Page.IsPostBack is always false even after AutoPostBack.
EDIT 2:
The answer was in the Server Transfer. In a distant control loaded from the master page, the URL is inspected and rerouted before it hits the page, effectively negating my postback. I didn't see it before because I had added the breakpoints only in the target page.
I would check to make sure that you don't have validation somewhere interfering with the postback. To check this, set CausesValidation to false on the DropDownList.
Are you resetting the value of your dropdown in your PageLoad?
Also you may want to think about using an UpdatePanel so that it doesnt reload the whole page.
Is it inside an UpdatePanel? If yes, set ChildrenAsTriggers="true"
Based on the attempts you've mentioned, as well as the comments regarding the update panel, I attempted a few things.
By setting the data source on the load event, you will only do it once:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//set up data here
}
}
You may use the Page.IsPostBack code and the method of yours to get what you want:
if (Page.IsPostBack)
{
//do page reload logic in here
}
protected void foo(object sender, EventArgs e)
{
//get your selected value here
}
(Note: Both of the postback conditionals are in the page load event)
EDIT:
Here's the whole setup, its basic, but you get the idea:
As you can see when I made a selection from cat to dog, it recognized that there was a postback, so it skipped the databind and set t. I could only assume there's something else here that I'm not seeing if you can't get it to ever return true for you on postback.

What is the effect of IsPostBack Condition?

I have a aspx Page where I am using AJAX. like
<asp:UpdatePanel runat="server" ID="upPanelDDLProgram">
<ContentTemplate>
<asp:DropDownList ID="DDLProgram" runat="server" Width="194px" Height="18px" OnSelectedIndexChanged="OnDDLProgramChanged" AutoPostBack="true">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
and my code behind is like
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
//{
// BindProgramDDL();
//}
BindProgramDDL();
}
protected void BindProgramDDL()
{
List<CcProgramEntity> programEntities = FormSaleSubmit_BAO.GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = FormSaleSubmit_BAO.GetAllPrograms();
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
the If condition is the page load event, is commented out. If I toggle the comment part of the page load event, it works perfect in both cases. My question is why is this heppening?
IsPostBack tells you if it is a second request to the page. The benefit here is if you need to do anything costly, such as a database call to fill a dropdownlist or similar, you can do it when !IsPostback, then use ViewState to retain the values.
To put it specific to your situation
Using:
if (!IsPostBack)
{
BindProgramDDL();
}
Will result in BindProgramDDL being called ONLY on the first time the page is loaded, all AJAX or other user interaction with the page will NOT call BindProgramDDL;
Without that, in place EVERY page load would call the method, un-necessarily hitting the database for the records.
If I am getting you correct .......
DropDown list has data even you are not binding it second time after post back..........its becasuse its server side control and each serverside control has its view state with it thats y its not removing data.
IsPostBack - it true when do the post back by using serverside control like dropdown, checkbox , textbox............When you load page first time this property is false but in subsequent request to same page value of this property is true. you can check msdn document for more detail about it.
It's basically saying are you visiting the page for the first time (not a post back), or has the user clicked on a control (a post back).
Useful for when you only want to run methods once when the page is initially loaded
You're code should probably look like this to achieve best results
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindProgramDDL();
}
}
I suspect that the DropDownList saves the items in the ViewState and then work with them during all subsequesnt requests. That is why your code works even if the editor's DataSource is set only when IsPostBack returns false.
PostBack event appears on every action (ajax too), except of first page load.
Page.IsPostBack
indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
see http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
Since you've bound your datasource the first time the page was loaded, the data are still in the viewstate and you don't need to update the control (unless the datasource has changed).
Take also into account that, since you're using ajax, you may also want to intercept if there was an 'asynchronous postback'.
See http://encosia.com/are-you-making-these-3-common-aspnet-ajax-mistakes/

Linkbutton postback-url changes after second time of sorting/paging

I have a asp.net page which has been url rewritten and when im sorting my gridview or paging it via my custom pager it works.
This works fine for first postback to the using the update panel, but 2nd
postback the url has changed to the wrong url. When u view source the form
action= is still point to correct url, but updatepanel / datagrid is ignoring
this and using some other url.
why and how can i ensure this url is always the rewritten version used for
updatepanel postbacks?
Solved:
protected void Page_Load(object sender, EventArgs e)
{
form1.Action = Request.RawUrl;
}

Categories