Add postbackurl as a attribute to button - c#

I have a button, which OnClick stores some text to tables in a database.
All this in asp.net using c# and .NET Framework 4.0.
However, i need that, when click, the button executes the OnClick method, thing is doing right now, but ALSO, navigates to another page, to continue registration.
The registration form is about 9 pages, i know if i pass postbackurl="url" it navigates to another page/form, but then it doesn't executes the OnClick method.
<div style="text-align:right; margin-top:20px"><asp:Button ID="Button1" runat="server" ValidationGroup="Curriculum" postbackurl="Envia2.aspx" OnClick="Button1_Click" CssClass="my_btn" /></div>
So, how can i 'attach' this attribute to the OnClick method?
Or there is another walkaround to this situation?
Thanks in advance!

Button click event cannot perform both at the same time at client side - submit to server and redirect to another page.
Ideally, you do not want to insert each registration step into database. instead, you want to store them in session state. Then insert them into database at the final page.
Here is the example. Make sure you check validation on each step -
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string Other { get; set; }
}
// Page1.aspx
<asp:Button runat="server" ID="SubmitButton" Click="SubmitButton_Click"
Text="Continue to Step 2" />
// Page1.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
var customer = new Customer
{
FirstName = FirstNameTexBox.Text,
LastName = LastNameTexBox.Text
};
Session["Customer"] = customer;
// Redirect to page 2
Response.Redirect("Page2.aspx");
}
// Page2.aspx
<asp:Button runat="server" ID="SubmitButton" Click="SubmitButton_Click"
Text="Continue to Step 3" />
// Page2.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
var customer = Session["Customer"] as Customer;
customer.Address = AddressTextBox.Text;
Session["Customer"] = customer;
// Redirect to page 3
Response.Redirect("Page3.aspx");
}
// Page9.aspx
<asp:Button runat="server" ID="SubmitButton" Click="SubmitButton_Click"
Text="Submit" />
// Page9.aspx.cs
protected void SubmitButton_Click(object sender, EventArgs e)
{
var customer = Session["Customer"] as Customer;
customer.Other = OtherTextBox.Text;
// Save customer to database.
}

If I understand your question, you need to do two things when the user clicks the button:
Call "Button1_Click"
Post to "Envia2.apsx"
The problem is that 1. is itself consists of a form post to the current page (as you may know, ASP.Net server controls, in order to handle events on the server side, trigger a postback behind the scenes). So I could see a few options:
Use OnClick and remove postbackurl -- inside the click handler, redirect to "Envia2.aspx"
Remove both OnClick and postbackurl. Instead, make an Ajax call of some kind to invoke the "Button1_Click" code, and then when complete, call form.post() on the form that "Button1" belongs to.

Related

ASP.NET: add postback to anchor

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'
}
}

Why doesn't asp.net button work?

I have used this behind asp button click function. It works on local system but not after begin deployed on server. Why ?
public void EmployeeDeActivation()
{
hdnfieldSessionPersonalInfoID.Value = "0";
Session["ExtraPersonalInfoID"] = 0;
Response.Redirect("EmployeeInformation.aspx", false);
}
.aspx code:
<asp:Button ID="btnEmployeeActivated" runat="server" Visible="false" OnClick="btnEmployeeActivated_Click"
CssClass="btn btn-rounded pull-right btnEmployeeActivated" />
i.e. when i click button when on local system, it hits then button event and refrehes the page but when it doesn't work like then button click never hits.
Update:
protected void btnEmployeeActivated_Click(object sender, EventArgs e)
{
try
{
EmployeeDeActivation();
}
catch (Exception ex)
{
throw;
}
}
Doesn't this method need to accept an event handler? E.g.
protected virtual void OnClick(
EventArgs e
)
Also, the part of code where you set your hidden is not needed as you redirect after.
Also it has the wrong name as it doesn't match the onclick name
Try to enable Trace and log on every method in the page. Try to visualize what your code is doing during postback.
Another useful tool is Glimpse.
Hope it helps!
asp button property "Visible" is set to false in your code. how come button is rendering at first place ?

ASP.NET call onclick function with parameter

In my code a user can like a post when they click on the following code:
<li><%# Eval("Likes") %></li>
This will run the function LikePost in the codebehind:
public void LikePost(object sender, EventArgs e)
{
//like post whit given id using a database query
}
but how can I give that function a parameter, because it needs the postid from the post that the user is going to like.
Instead of an HTML link, use an asp:LinkButton which has a CommandArgument property. Something like this:
<asp:LinkButton
ID="LinkButton1"
Text='<%#Eval("Likes")%>'
CommandArgument='<%#Eval("ID")%>'
OnCommand="LikePost"
CssClass="icon fa-heart"
runat="server"/>
Then in your code-behind the signature takes a CommandEventArgs:
public void LikePost(Object sender, CommandEventArgs e)
{
// e.CommandArgument should contain the desired value
}

Client Interaction in WebForms

What way is standard/ recommended to do the following:
When a user raises the Page_Command "Save" or "Send," I want to run a method. If the method returns false, I want to send the user back to the page and display a message.
All of the data they entered in the form should still be there. The message would have a button that reads, "Send Anyway/ Regardless." If they click it, it will send.
I know I could do this via a webservice and jQuery, but I am asking how I would do this via WebForms.
Here is my basic code:
protected void Page_Command(Object sender, CommandEventArgs e)
{
if ( e.CommandName == "Save" || e.CommandName == "Send" )
{
// run method
}
}
There are several ways you could do this.
One option might be to a button with the text "Save", and another with the text "Send anyway". Make the second button invisible to begin with, and the first visible.
When the first button is clicked, it should run the validation-logic. If validation succeeds, submit - otherwise, hide the first button, and set the other one to visible.
When / if the second button is clicked, the submit is performed without validation.
Update:
With some minor modifications, you should be able to do something like this:
Markup:
<asp:Button runat="server"
ID="myFirstButton"
OnClick="SubmitWithValidation" />
<asp:Button runat="server"
ID="mySecondButton"
Visible="False"
OnClick="SubmitData" />
Code:
protected void SubmitWithValidation(object sender, EventArgs e)
{
if (ValidateMyData())
{
SubmitData(sender, e);
}
else
{
mySecondButton.Visible = true;
myFirstButton.Visible = false;
}
}
private bool ValidateMyData()
{
// Validate stuff
return isValid;
}
private void SubmitData(object sender, EventArgs eventArgs)
{
// Logic to submit your data here
}

C# / asp.net global Variables?

I have two buttons with on click functions
The 1st one gets assigned a variable when Clicked.
How do I get my second button to get the variable from the 1st button when I click button 2?
It doesn't seem to work. As the second button doesn't recognise the Variable.
Thanks
EDIT:
Just to clarify My code is generating a pdf. button 1 selects the url of the template to use. and in button 2 (the one generating the pdf) I want it to get the variable set from button 1 so it knows what template to use.
EDIT 2:
My code does work but only when I'm not using the ajax update panel. it seems that the variable I'm trying to set doesn't get set with AJAX
Your Button have Id, you get this button with his Id
Nota : You can add runat="server" in order to visualize in server side
<asp:Button id="Button1"
Text="Click "
OnClick="Btn1_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Click "
OnClick="Btn2_Click"
runat="server"/>
void Btn2_Click(Object sender, EventArgs e)
{
Button1.Text = "test after click on button 2";
Template = ...;//Set your value
}
void Btn1_Click(Object sender, EventArgs e)
{
Button2.Text = "test after click on button 1";
//Here you can get your value after post.
var result = Template;
}
It's not subject but in delegate you can also get objet button by passing on sender argument.
var button = sender as Button; //You get button who raise event
In order to manage Template Path property.
public string Template
{
get
{
if(ViewState["Template"] != null)
{
return (string)ViewState["Template"];
}
}
set{ViewState["Template"] = value;}
}
i guess you are looking at accessing value of a variable inside the click event of button2 for which the value is set in the button1 click event ?
private string myPrivateString = "";
void Page_Load()//Not sure of correct method signature
{
if(Page.IsPostBack)
{
myPrivateString = Session["myPrivateString"];
}
}
void Button1_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
myPrivateString = "Value Set From Button 1";
Session["myPrivateString"] = myPrivateString;
}
void Button2_Click(object sender, EventArgs e)
{
//There will a postback before this gets executed
//Accessing myPrivateString here without setting value from session
//will return empty string as after PostBack its a new page thats rendered.
myPrivateString = Session["myPrivateString"]; // Or do it in the Page_Load event
}
I guess now you can get the value of inside the button2 click event.
Also read about ASP.NET Page lifecycle and how client side events like button clicks are handled by the ASP.NET framework.

Categories

Resources