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'
}
}
Related
I'm wondering what is my issue on passing a variable from page to page using asp.net session.
I've stripped the code down to just one text box to see whats going on. I'm just trying to take the value of a text box and display it on a confirmation page. When the button is clicked it transfers me to the second page but there label is blank. Yes my post back url is pointing to the second page.
Here is the button click:
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
}
Here is the page load of the second page:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = (string)(Session["name"]);
}
Unless I've been looking at this to long and missed something. I've already read "How to: Read Values from Session State" from MSDN.
You say that you've set the PostBackUrl to your second page. If you're going to do it that way, you need to use Page.PreviousPage to get access to your textbox. But this is the easiest way:
Firstly, leave the PostBackUrl alone. Setting the PostBackUrl to your second page means that you're telling the SECOND PAGE to handle your button click, not the first page. Hence, your session variable never gets set, and is null when you try to pull it.
This should work for ya.
And yes, you can also do this with a QueryString, but if its something that you don't want the user to see/edit, then a Session variable is better.
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
Response.Redirect("PageTwo.aspx");
}
Then in the second page (You don't REALLY need the ToString()):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
lblName.Text = Session["name"].ToString();
}
}
EDIT -- Make sure that your button click actually gets fired. Someone can correct me wrong on this, as I do most of my work in VB.NET, not C#. But if you don't specify the OnClick value, your function won't get called.
<asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="submit_Click" />
The code you have posted looks fine, so your problem is probably with setup.
Check this link ASP.NET Session State Overview and pay particular attention to the sections on Cookieless SessionIDs and Configuring Session State.
I don't think you added the session. This is how I have done mine.
First Page
protected void btnView_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbxCheckDates.Items)
{
if (li.Selected == true)
{
lblMessage.Text = "";
string checkDate = lbxCheckDates.SelectedItem.Text;
Session.Add("CheckDates", checkDate);
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('Paystub.aspx','_newtab');", true);
}
}
}
Second Page
protected void Page_Load(object sender, EventArgs e)
{
string checkDate = (string)(Session["CheckDates"]);
//I use checkDate in sql to populate a report viewer
}
So with yours, I think you need..
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session.Add("Name", name);
}
I think what you have in the second page should work, but if it doesn't, add ToString() to it like..
lblName.Text = (string)(Session["name"]).ToString();
Let me know if this helps!
Are you doing a redirect after setting the session variable on the first page, if so you it will not work correctly (unless you know the trick). Checkout this article on making it work. Basically, the way to make this work is to the overload redirect method.
Response.Redirect("~/newpage.aspx", false);
The false parameter prevents .net from terminate processing on the existing page (that actually writes out the session state)
For Second Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value"] != null)
{
Label1.Text = Session["value"].ToString();
}
else
{
Label1.Text = "Sorry,Please enter the value ";
}
}
You can use Server.Transfer() instead of Response.Redirect()
For first page, use this:
protected void Button1_Click(object sender, EventArgs e)
{
string value = TextBox1.Text;
Session["value"] = value;
Response.Redirect("~/Sessionpage.aspx");
}
I'm still new at this so I will try to explain my problem the best I can. English is not my first language so I apologize if I use some terms incorrectly.
I have a 100 line code that is executed every time a button is pressed. My problem is, I have 20 buttons and they all contain the same code (they are only slightly different in means of grabbing info from different source). Is there any way to do this instead of copying the same code too many times.
Basically my code is this:
private void button1_Click(object sender, EventArgs e)
{
//file data source url
sourceUrl = ("www.myurl.com")
//Grab data
code
code
code
//Store data
code
code
code
//Write data
code
code
code
}
Every button has the same code except for the "sourceUrl" part. If I want to add more buttons I have to copy>paste the whole code and my application is starting to get HUGE. Is there any way to shrink the code by only having the code once, and then calling an action or method every time the button is pressed. So instead of having 100 line code multiple time, I'll have one line code for each button and one 100 line code on the top that will be the source for that one line code.
Thanks in advance
Use the Tag property of your buttons to store the source url string and then set, for every button, the same event handler
private void buttonCommonHandler_Click(object sender, EventArgs e)
{
Button b = sender as Button;
CommonMethod(b.Tag.ToString());
}
private void CommonMethod(string sourceUrl)
{
// Execute the common code here....
}
You could set the common handler and the Tag using the form designer window or you could do that dynamically mimicking the code prepared for you by the designer in the InitializeComponent call
button1.Click += buttonCommonHandler;
button1.Tag = "www.myurl.com";
button2.Click += buttonCommonHandler;
button2.Tag = "www.anotherurl.com";
That's what functions are for. Use this layout:
private void YourFunc(string sourceUrl)
{
//Grab data
code
//Store data
code
//Write data
code
}
Now your buttons' event handlers look like this:
private void button1_Click(object sender, EventArgs e)
{
YourFunc("www.myurl.com");
}
private void button2_Click(object sender, EventArgs e)
{
YourFunc("www.myurl2.com");
}
Sure there is a way. Just make the whole function a function that takes the url as a string parameter. And then call that function from your code behind.
private void button1_Click(object sender, EventArgs e)
{
//file data source url
ProcessData("www.myurl.com");
}
private void ProcessData(string sourceUrl)
{
//Grab data
code
code
code
//Store data
code
code
code
//Write data
code
code
code
}
Here we can use use CommandName property, by passing URL in every button's CommandName property and passing it as a parameter to your Common Method to fetch data , So you can create a single function and call it through you btn_Click event .
<asp:Button ID="button1" runat="server" Text="clickMe"
CommandName="put your URL here" OnCommand="button1_Click" />
<%--OnClick="button1_Click" />--%>
See here we can pass your 'URL' in CommandName property ,few things to keep in mind , Here we are using OnCommand event rather than OnClick event of button , so that we can use 'CommandName' property here .1. OnCommand MSDN
2. Commandname MSDN
// private void button1_Click(object sender, EventArgs e)
private void button1_Click(object sender, CommandEventArgs e)
{
string sourceUrl = Convert.tostring(e.CommandName)
// Call function to grab data pass URL as parameter.
GrabDate (sourceUrl ) ;
So now we can get the URL value from button CommandName property .
3 . EventArgs Class
4 .CommandEventArgsClass
I have a aspx page name MakeRedemption.aspx, in which have a UserControl (Search.ascx).
There is Page_Prerender() in the MakeRedemption.aspx.
I would like to ask, how can I call the Page_Prerender() from MakeRedemption.aspx, by a function in Search.ascx.
It is something as follow :
Actually there is a looping in one of the function in my User Control page.
The Page_Prerender (MakeRedemption.aspx) will trigger after all the loop finish.
What I want is :
Everytime before end of each itme of the loop, I will like to trigger the Page_Prerender on the MakeRedemption.aspx to do something.
Something like :
for (int i = 0 ; i < 10 ; i ++)
{
//some code here
// I would like to trigger Page_Prerender here to do something before end of the loop.
} // the Page_Prerender (in MakeRedemption.aspx) trigger after all the loop finish.
Means that, this for loop has i = 10, thus, I would like to trigger the Page_Prerender 10 times inside the for loop.
My PreRender function in the aspx file is as follow :
protected void Page_Prerender(object sender, EventArgs e)
{
//some code here
}
Not sure this Page_Prerender() is consider as the auto generate OnPreRender() or not.
I would like to trigger this Page_Prerender() instead of OnPreRender() .
Sorry if I am asking a stupid question, I am new in programming and c#.
Kindly advise.
Thanks.
Finally i find the way to do it, the oodng is as follow :
Add this following code in the aspx.cs page:
delegate void DelMethodWithoutParam();
protected void Page_Load(object sender, EventArgs e)
{
DelMethodWithoutParam delParam = new DelMethodWithoutParam(Page_prerender);
this.ucSearchGifts.PageMethodWithNoParamRef = delParam;
}
Page_prerender(){
//some code here...
}
and add this following code in the user control cs page:
private System.Delegate _delNoParam;
public Delegate PageMethodWithNoParamRef
{
set { _delNoParam = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
_delNoParam.DynamicInvoke();
}
When click on the Button1 in user control page, the Page_prerender() in aspx page, which is parent page, will be trigger.
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);
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If page loads for first time
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); // Assign the Session["update"] with unique value
//=============== Page load code =========================
//============== End of Page load code ===================
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString()) // If page not Refreshed
{
//=============== On click event code =========================
Label1.Text = TextBox1.Text;
//lblDisplayAddedName.Text = txtName.Text;
//=============== End of On click event code ==================
// After the event/ method, again update the session
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else // If Page Refreshed
{
// Do nothing
}
}
protected override void OnPreRender(EventArgs e)
{
ViewState["update"] = Session["update"];
}
}
This is not working for high resolution gradient background.
Consider wrapping your button and the label in an updatepanel control, which uses AJAX to refresh their contents.
The rest of the page will not be reloaded and the action will not affect the browser navigation.
See this page on how an updatepanel control works.
Since you are handling the button click event in server side there has to be a postback to handle it.
If you do not want a post back to happen change the event handling to "client click"
//Heinzi code worked for me just made a small change in OnPreRender event, assign the ViewsState value when its not post back
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
ViewState["update"] = Session["update"];
}
}