On page load I add a new attribute (UploadStatus) to an ImageButton (FileUpload_result) from code behind. Now on button click I want to retrieve the value of the added attribute. How can I do that?
public string UploadStatus = "testing";
protected void Page_Load(object sender, EventArgs e)
{ FileUpload_result.Attributes.Add("UploadStatus", UploadStatus); }
<asp:ImageButton runat="server" ID="FileUpload_result" OnClick="FileUpload_Click" ImageUrl="icon-ok.png" UploadStatus="testing" />
protected void FileUpload_Click(object sender, EventArgs e)
{ // How can I get the value of the added attribute UploadStatus? The value is testing in this case}
In your FileUpload_Click method you can access the attribute like this.
((ImageButton)sender).Attributes["UploadStatus"]
Something like FileUpload_result.Attributes[""UploadStatus"] might get it. https://msdn.microsoft.com/en-us/library/kkeesb2c%28v=vs.140%29.aspx
Related
In my javascript file, I got an ajax to get all list and iterate these data and append <a id='userID' class='btn'>Assign ID<> to my list.
So, how do a add postback to these anchor and redirect it inside my method in the server. Below is my code but didn't work. When I click the achor button, it just redirect/refresh to the same page without doing any changes and didn't show the text.
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick='javascript:__doPostBack('uniqueID','')'>Assign ID</a>
protected void Action_assignID(object sender, EventArgs e)
{
// assign ID action
Response.Write("Pass");
}
You should be changed your button to:
<a id='uniqueID' class='btn assignID' href='javascript:void(0);' onclick="javascript:__doPostBack('uniqueID','Assign ID')">Assign ID</a>
And it's a good idea to implement the IPostBackEventHandler interface in your codebehind as below:
public partial class WebForm : Page, IPostBackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
public void RaisePostBackEvent(string eventArgument)
{
// do somethings at here
}
}
Hope this help!
The __doPostBack method really doesn't do anything special except, well... perform a POST operation back to the same page with two specific form arguments.
The first parameter is the __EVENTTARGET and the second parameter is the __EVENTARGUMENT.
The magic all happens in ASP.Net where it automagically wires up your controls to event handlers, but since you are creating these entirely in JavaScript the server doesn't know that those controls exist.
However, you can manually grab these values and do something with them.
//Client Side JavaScript:
__doPostBack('my-event', '42');
//Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var target = Request.Params["__EVENTTARGET"];
var args = Request.Params["__EVENTARGUMENT"];
Target.Text = target; // 'my-event'
Argument.Text = args; // '42'
}
}
I have the following code :
protected void Page_Load(object sender, EventArgs e)
{
string runat = "runat=\"server\"";
}
protected void Page_PreRender(object sender, EventArgs e)
{
//some code
}
<iframe <%=runat%>></iframe>
I need to be sure the code within Page_PreRender executes only when the variable runat has been initialized & the iframe control is ready for rendering.
Unfortunately it does not work. I also tried Page_PreRenderComplete and it does not work.
Does anyone have an idea to fix this problem ?
Thanks!
Create a PlaceHolder in your markup and then add the iframe programmatically to the PlaceHolder as a LiteralControl, like this:
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl("<iframe src='something.aspx'></iframe>"));
}
I created a asp:Repeater that I fill with .ascx controls:
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.DataSource = listOfData;
Repeater1.DataBind();
}
On page I have:
<uc:Product runat="server"
ImportantData='<% #Eval("ImportantData") %>'
id="DetailPanel1" />
Inside Product.ascx.cs I have:
public int ImportantData{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
On Product.ascx I have:
<asp:ImageButton ID="btn_Ok" runat="server"
onclick="btn_Ok_Click"
ImageUrl="~/image.png" />
Problem is when I click on image button I get error:
A critical error has occurred. Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page...
I have tried to change first code to this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Repeater1.DataSource = listOfData;
Repeater1.DataBind();
}
// Repeater1.DataBind(); // and tried to put DataBind() here
}
But then when I click on image button ImportantData is empty.
What I did wrong here?
PageLoad is happening before your postback event, change your event to PreRender:
protected void Page_PreRender(object sender, EventArgs e)
{
Repeater1.DataSource = listOfData;
Repeater1.DataBind();
}
This will bind your repeater after the postback and maintain your postback value.
Edit:
Here's a good picture showing the entire WebForms page lifecycle:
As you can see
ProcessPostData event is called AFTER Load event.
So you want to bind your Repeater after the PostData has been processed.
This can be done on PreRender
The problem is not that you are calling data bind in the wrong place, but most likely that the user control is not saving the data in viewstate correctly. It looks like you are using a custom control. What you can do if this is the case is to create a property on your user control that reads from the viewstate. Here is an example:
Public Property ImportantData() As Int32
Get
Return ViewState("_ImportantData")
End Get
Set(ByVal value As Int32)
ViewState("_ImportantData") = value
End Set
End Property
This will allow your data to persist and the necessary data to be present on postback.
and doing this is correct so that it only loads on the initial load.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Repeater1.DataSource = listOfData;
Repeater1.DataBind();
}
// Repeater1.DataBind(); // and tried to put DataBind() here
}
I am facing problem in query string. Following is my asp code
<asp:Label ID="Lable1" runat="server" Text="" ></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Lable1.Text += Request.QueryString["refresh"] ;
Response.Redirect("QueryString1t.aspx?refresh=" + 1 + "");
}
Up to my knowledge Lable1 text should change on button click every time. Lable1 text should not show any thing on page load . on button click it should be like for first click 1 for second click 11 and so on..
But it is not showing as my expectation .So tell me please where i am wrong?
You are redirecting after setting label text, wrong approach.
Try this: -
protected void Page_Load(object sender, EventArgs e)
{
Lable1.Text = Request.QueryString["refresh"];
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("QueryString1t.aspx?refresh=" +
string.IsNullOrEmpty(Request.QueryString["refresh"]) ? 0 :
Convert.ToInt32(Request.QueryString["refresh"]) + 1 + "");
}
OR this: -
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Lable1.Text = string.IsNullOrEmpty(Lable1.Text) ? "0" :
(Convert.ToInt32(Lable1.Text) + 1).ToString();
}
Have a look at this:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Particularly the fourth and fifth events in the cycle.
If you want the text to be updated as you are looking for there, then you need to put that code in the page load, not the click event handler.
In brief, you have to think of it like this: Every time you do a redirect, you lose viewstate,
http://msdn.microsoft.com/en-us/library/ms972976.aspx
which is the means by which ASP.NET keeps track of your updates to the controls, like in your event handler. So your update is immediately lost.
The next piece of code you will hit is your load event, so that is where you need to set the label's text property.
How do I persist the value of a label through a response.redirect?
I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}