LoginView inside FormView control is not databinding on PostBack - asp.net

I have a fairly simple form:
<asp:FormView>
<EditItemTemplate>
<asp:LoginView>
<RoleGroups>
<asp:RoleGroup roles="Blah">
<ContentTemplate>
<!-- Databound Controls using Bind/Eval -->
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
<!-- Databound Controls -->
</EditItemTemplate>
</asp:FormView>
<asp:LinqDataSource OnUpdating="MyDataSource_Updating" />
I handle my LinqDataSource OnUpdating event and do some work handling some M:N fields. That all works.
However, once the update is finished (and I call e.Cancel = true), the LoginView control does not databind its children... so they are all blank. The FormView's viewstate is still fine, as all the rest of the controls outside of the LoginView appear fine. I even handle the FormView_DataBound event and a Trace shows that the FormView is being databound on postback.
Why then is the LoginView not keeping its ViewState/being databound? Here's a sample code snippet showing the flow:
protected void MyDataSource_Updating(object s, LinqDataSourceUpdateEventArgs e)
{
try
{
Controller.DoSomething(newData);
// attempts to databind again here fail
// frmView.DataBind();
// MyDataSource.DataBind();
// LoginView.DataBind();
}
catch { // blah }
finally
{
e.Cancel = true;
}
}

I fixed this by reverting to the age old method of databinding everything myself and axing the LoginView.

Ok, i don't know if you need help at this time, but the contaiter that you need to catch is de FormItem, in this case you cant do this
<%# DataBinder.Eval(((FormItem)Container.Parent).DataItem,"YOUR FIELD") %>
Sorry for my english.
Bye.

Related

DropDownList's SelectedIndexChanged event not firing

I have a DropDownList object in my web page. When I click on it and select a different value, nothing happens, even though I have a function wired up to the SelectedIndexChanged event.
First, the actual object's HTML code:
<asp:DropDownList ID="logList" runat="server"
onselectedindexchanged="itemSelected">
</asp:DropDownList>
And this is that function, itemSelected:
protected void itemSelected(object sender, EventArgs e)
{
Response.Write("Getting clicked; " + sender.GetType().ToString());
FileInfo selectedfile;
Response.Write("<script>alert('Hello')</script>");
foreach (FileInfo file in logs)
{
if (file.Name == logList.Items[logList.SelectedIndex].Text)
{
Response.Write("<script>alert('Hello')</script>");
}
}
}
None of the Responses appear, and that portion of JavaScript is never run. I've tried this on the latest 3.6 version of Firefox, as well as Internet Explorer 8. This is being served from a Windows Server 2003 R2 machine, running ASP.NET with the .NET Framework version 4.
Set DropDownList AutoPostBack property to true.
Eg:
<asp:DropDownList ID="logList" runat="server" AutoPostBack="True"
onselectedindexchanged="itemSelected">
</asp:DropDownList>
try setting AutoPostBack="True" on the DropDownList.
I know its bit older post, but still i would like to add up something to the answers above.
There might be some situation where in, the "value" of more than one items in the dropdown list is duplicated/same. So, make sure that you have no repeated values in the list items to trigger this "onselectedindexchanged" event
Add property ViewStateMode="Enabled" and EnableViewState="true"
And AutoPostBack="true" in drop DropDownList
Also make sure the page is valid.
You can check this in the browsers developer tools (F12)
In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property
If the page is not valid the form will not submit and therefore not fire the event.
For me answer was aspx page attribute, i added Async="true" to page attributes and this solved my problem.
<%# Page Language="C#" MasterPageFile="~/MasterPage/Reports.Master".....
AutoEventWireup="true" Async="true" %>
This is the structure of my update panel
<div>
<asp:UpdatePanel ID="updt" runat="server">
<ContentTemplate>
<asp:DropDownList ID="id" runat="server" AutoPostBack="true" onselectedindexchanged="your server side function" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Instead of what you have written, you can write it directly in the SelectedIndexChanged event of the dropdownlist control, e.g.
protected void ddlleavetype_SelectedIndexChanged(object sender, EventArgs e)
{
//code goes here
}

What is the purpose of EnableEventValidation and how does it work?

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" onrowediting="GridView1_RowEditing">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" />
<asp:Label ID="lblFirstColumn" runat="server" Text='<%# Eval("FirstColumn") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditMode" runat="server" Text="This is Edit mode"></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("FirstColumn", typeof(int));
dt.Rows.Add(100);
GridView1.DataSource = dt;
if (!IsPostBack)
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
If I change if (!IsPostBack) GridView1.DataBind(); to GridView1.DataBind(); and try to put GridView into Edit mode by clicking btnEdit, then I get the exception:
Invalid postback or callback argument.
Event validation is enabled using
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.
But if I set EnableEventValidation to false, then GridView1 won’t enter edit mode ( ie - GridView1_RowEditing doesn’t get called ).
BTW – same problem also occurs with other databound controls ( DataList, DetailsView )
Page. EnableEventValidation gets or
sets a value indicating whether the
page validates postback and callback
events. When the EnableEventValidation
property is set to true, ASP.NET
validates that a control event
originated from the user interface
that was rendered by that control. A
control registers its events during
rendering and then validates the
events during postback or callback
handling.
a) Why must postback and callback events be evaluated? and how exactly does evaluation happen?
b) Why would calling GridView1.Databind() on each postback cause exception when trying to put it into edit mode?
c) I also don’t see any reasons why disabling EnableEventValidation prevents GridView from entering edit mode?! Thus why did
thank you
There is a good article about how and why you would want to use EventValidation here:
http://odetocode.com/blogs/scott/archive/2006/03/21/asp-net-event-validation-and-invalid-callback-or-postback-argument-again.aspx
and MSDN:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableeventvalidation.aspx
The short answer is event validation is designed to protect the web site from having values injected into the page that can be used to exploit your application in some way.

Why aren't all controls initialised at the event handling point of the ASP.NET page lifecycle?

I have a user control embedded in a web part. It has the following snippets of code:
protected TextBox searchTextBox;
protected Button goButton;
protected Button nextButton;
protected Repeater pushpins;
protected Label currentPageLabel;
protected void goButton_Click(object sender, EventArgs e)
{
// Do stuff
}
<asp:TextBox ID="searchTextBox" runat="server" />
<asp:Button ID="goButton" runat="server" Text="Go" OnClick="goButton_Click" />
<asp:Repeater ID="pushpins" runat="server" EnableViewState="false">
<ItemTemplate>Blah</ItemTemplate>
</asp:Repeater>
<asp:Label ID="currentPageLabel" runat="server" />
<asp:Button ID="nextButton" runat="server" Text=" >> " OnClick="nextButton_Click" />
(There is no OnLoad or CreateChildControls method.)
If I place a breakpoint on the first line of goButton_Click, I find:
searchTextBox: initialised
goButton: initialised
nextButton: NULL
pushpins: initialised
currentPageLabel: NULL
Why are some controls initialised and others not? How do I get around this if I'd like to update the Text property on currentPageLabel?
Update:
I've placed breakpoints all the way through the page life cycle and found that nextButton and currentPageLabel are never initialised. The breakpoints were placed at OnLoad, CreateChildControls, goButton_Click, OnPreRender, Render and OnUnload.
Is it possible you've inadvertently got local variables named currentPageLabel and/or nextButton declared somewhere? The compiler will happily allow this...
This is especially common in a move from ASP.NET 1.1 to 2.0 or higher, since the way the designer defined these controls changed.
The problem was that all of the controls that weren't being initialised were inside a HeaderTemplate within a Repeater control. (To save space I didn't paste all of my code into the question, dang it.)
I moved them out and the problem is resolved. Obviously controls in the HeaderTemplate are instantiated by the Repeater and do not follow the normal page life cycle.

ASP.NET: "Object Required" when repeating LinkButtons in an UpdatePanel

I have an UpdatePanel which has a Repeater repeating LinkButtons. When I click a LinkButton, the page does a partial postback, then I get a javascript error: "Object required". I tried debugging the javascript, but couldn't get a call stack. If I remove the UpdatePanel, the LinkButtons do a full postback, and they disappear from the page. How can I get this UpdatePanel to work?
<ajax:UpdatePanel ID="wrapperUpdatePanel" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Repeater ID="endpointRepeater" runat="server" OnItemDataBound="EndpointDataBound">
<HeaderTemplate>
<div class="sideTabs">
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="endpointLink" runat="server" OnClick="EndpointSelected" />
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</div>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</ajax:UpdatePanel>
binding code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.SelectedEndpoint = Factory.Get<IEndpoint>(Enums.EndPoints.Marketing);
}
IEndpointCollection col = EndpointCollection.GetActivelySubscribingEndpointsForPart(this.Item);
if (this.Item.IsGdsnItem)
col.Add(Factory.Get<IEndpoint>(Enums.EndPoints.Gdsn));
if (col.Count > 0)
col.Insert(0, Factory.Get<IEndpoint>(Enums.EndPoints.Marketing));
this.endpointRepeater.DataSource = col;
this.endpointRepeater.DataBind();
if (this.endpointRepeater.Items.Count > 0)
{
LinkButton lb = this.endpointRepeater.Items[0].FindControl("endpointLink") as LinkButton;
this.EndpointSelected(lb, new EventArgs());
}
}
thanks,
mark
This may not be your main issue, but when including an object inside a Repeater that needs an event, you shouldn't be using that control's native events. Instead you should use the Repeater's OnCommand event.
If I were to guess, your problem is caused by the repeater not maintaining its DataBound state across PostBacks. The Linkbutton disappears from view because it is not bound to the page on every PostBack, so when the response is sent back to the client, it has nothing bound to it.
It sounds like the UpdatePanel is expecting the same (or similar) markup to be returned from the AJAX response as what is on the page already, so returning nothing for the repeater causes problems.
Try binding your repeater to the page/control in its OnInit() method. This should allow the ViewState for the repeater to be loaded on every PostBack.

ASP.NET linkbutton visible property issue

I'm using a public variable called IsAdmin in the code behind of an aspx page.
public partial class _news : System.Web.UI.Page
{
public bool IsAdmin = false;
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.Name.Contains("admin"))
{
IsAdmin = true;
}
else
{
IsAdmin = false;
}
}
And i use the property Visible='<%#IsAdmin%>' to assign to panels which i want to show if the user is an admin in the aspx design of the page. Strangely it works for the linkbuttons i've put on the repeater.
<asp:Panel ID="Panel1" runat="server" Visible='<%#IsAdmin%>'>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl='<%# "news_edit.aspx? Action=edit&id=" + Convert.ToString( Eval("news_id")) %>Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" PostBackUrl='<%# "news.aspx?Action=delete&id=" + Convert.ToString( Eval("news_id")) %>'>Delete</asp:LinkButton>
</asp:Panel>
and it works fine, however outside the repeater i've put another linkbutton without a panel
<asp:LinkButton ID="LinkButton4" runat="server" PostBackUrl="~/news_edit.aspx?action=new" Visible='<%#IsAdmin%>'>Add New Item</asp:LinkButton>
but the visible property doesn't work on it! I tried putting it inside a panel too and setting it's visible property but that too didn't work.
So i have following doubts
1)what is the issue?
2)what is the technical name when we use references like '<%#IsAdmin%>' in the design page
3)Does page load happen before page is rendered of after page is rendered?
Thanks
<%# %> is the syntax used for accessing databound fields. Since you are likely databinding the Repeater control at some point, these expressions will be evaluated.
Since you are likely not calling databind on the Panel and the Linkbuttons outside of the Repeater, these expressions will not be processed. You can probably change them to something like
<%= IsAdmin.ToString() %>
and get the result you want.
Check this great blog entry for more information on the differences.
Also, Page Load happens before the page is rendered. Rendering the page is the last thing that happens in the ASP.Net page lifecycle.

Resources