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 ?
Related
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
}
I have created a custom cofirm message box control and I created an event like this-
[Category("Action")]
[Description("Raised when the user clicks the button(ok)")]
public event EventHandler Submit;
protected virtual void OnSubmit(EventArgs e) {
if (Submit != null)
Submit(this, e);
}
The Event OnSubmit occurs when user click the OK button on the Confrim Box.
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
OnSubmit(e);
}
Now I am adding this OnSubmit Event Dynamically like this-
In aspx-
<my:ConfirmMessageBox ID="cfmTest" runat="server" ></my:ConfirmMessageBox>
<asp:Button ID="btnCallMsg" runat="server" onclick="btnCallMsg_Click" />
<asp:TextBox ID="txtResult" runat="server" ></asp:TextBox>
In cs-
protected void btnCallMsg_Click(object sender, EventArgs e)
{
cfmTest.Submit += cfmTest_Submit;//Dynamically Add Event
cfmTest.ShowConfirm("Are you sure to Save Data?"); //Show Confirm Message using Custom Control Message Box
}
protected void cfmTest_Submit(object sender, EventArgs e)
{
//..Some Code..
//..
txtResult.Text = "User Confirmed";//I set the text to "User Confrimed" but it's not displayed
txtResult.Focus();//I focus the textbox but I got Error
}
The Error I got is-
System.InvalidOperationException was unhandled by user code
Message="SetFocus can only be called before and during PreRender."
Source="System.Web"
So, when I dynamically add and fire custom control's event, there is an error in Web Control.
If I add event in aspx file like this,
<my:ConfirmMessageBox ID="cfmTest" runat="server" OnSubmit="cfmTest_Submit"></my:ConfirmMessageBox>
There is no error and work fine.
Can anybody help me to add event dynamically to custom control?
Thanks.
The problem is not with the combination of the event being added late in the life cycle, and what you are trying to achieve with event handler.
As the error clearly states, the problem is with this line:
txtResult.Focus();
If you want to be able to set focus to controls, you must add your event handler on Init or Load.
You can work around this problem by setting the focus at client side using jquery.
var script = "$('#"+txtResult.ClientID+"').focus();";
You would have to emit this using RegisterClientScriptBlock.
The simplest change would be to move the focus() call:
bool focusResults = false;
protected void cfmTest_Sumit(object sender, EventArgs e)
{
txtResult.Text = "User Confirmed";
focusResults = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if(focusResults)
txtResult.Focus();
}
Are you sure txtResult.Text isn't being set again somewhere else?
I am trying to add a condition for a hyperlink that I have in my page.
Instead of just using a particular link like: Tutorial I want to display different pages for different users. For example, if the user is logged in as Admin, they will be presented with different link than regular users.
I have modified my hyperlink as: <a onclick="displayTutorial_Click">Tutorial</a>
and added this code:
protected void displayTutorial_Click(object sender, EventArgs e)
{
// figure out user information
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
System.Diagnostics.Process.Start("help/AdminTutorial.html");
else
System.Diagnostics.Process.Start("help/UserTutorial.html");
}
But this didn't work. Can anyone please help me to figure out how I can make the Tutorial link work properly? Thank you a lot in advance!!!
The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)
What you want is a server-side control, like the LinkButton:
<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>
This has an OnClick attribute that will call the method in your code behind.
Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Really, it would be best to check that you actually have a user first.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Wow, you have a huge misunderstanding how asp.net works.
This line of code
System.Diagnostics.Process.Start("help/AdminTutorial.html");
Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.
A very easy solution would be to change the href attribute of the link in you page_load method.
Your aspx code:
Tutorial
Your codebehind / cs code of page_load:
...
if (userinfo.user == "Admin")
{
myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else
{
myLink.Attributes["href"] = "help/otherSite.html";
}
...
Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.
this may help you.
In .cs page,
//Declare a string
public string usertypeurl = "";
//check who is the user
//place your code to check who is the user
//if it is admin
usertypeurl = "help/AdminTutorial.html";
//if it is other
usertypeurl = "help/UserTutorial.html";
In .aspx age pass this variabe
<a href='<%=usertypeurl%>'>Tutorial</a>
I found a solution like this but my onclick event is already tied to a code-behind handler:
MyButton.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(MyButton, "").ToString());
onclick="this.disabled=true;__doPostBack('MyContrl$MyButton','');"
My code:
<asp:imagebutton id="CheckoutBtn" runat="server" ImageURL="Styles/Images/submit.gif" onclick="CheckoutBtn_Click">
code-behind:
protected void CheckoutBtn_Click(object sender, ImageClickEventArgs e)
{
{
MyShoppingCart usersShoppingCart = new MyShoppingCart();
if (usersShoppingCart.SubmitOrder(User.Identity.Name) == true)
{
CheckOutHeader.InnerText = "Thank you.";
Message.Visible = false;
CheckoutBtn.Visible = false;
}
else
{
CheckOutHeader.InnerText = "Submission Failed - Please try again. ";
}
}
}
Disabling the Button serverside won't work, the Button will be disabled AFTER the PostBack, in this time the user can still click several times, disabling it in JavaScript this.disabled=true; is the only way to successfully do this.
Cases where you are trying to prevent the user from submitting a form multiple times are best handled using the Post/Redirect/Get pattern.
It is a very simple pattern and Wikipedia does a good job of explaining it:
http://en.wikipedia.org/wiki/Post/Redirect/Get
I assume you want to skip clicks that come within a certain TimeSpan of previous clicks. Create a class variable "DataTime LastClickTime", initially set to DateTime.MinValue. When you enter the click handler, check if DateTime.Now - LastClickTime > TimeSpan(...desired...) and if it isn't, exit the click handler with a return.
Try to disable the button with javascript instead of disabling it server side?
<asp:imagebutton id="CheckoutBtn" runat="server" ImageURL="Styles/Images/submit.gif" onclick="CheckoutBtn_Click" OnClientClick="this.disabled=true;">
One way is hide the button from Javascript and show some ajax loader image.
function btnClientClick()
{
document.getElementById('CheckoutBtn').style.display = 'none';
document.getElementById('dvLoader').style.display = '';
}
In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the page. To cut the story short, this doesn't work for me and I don't seem to be able to figure this out.
So, as my project is quite involved, I decided to create a short example that doesn't work either but if you can tweak it so that it works, that would be great and I would then be able to apply your solution to my original problem.
The following example should dynamically create three buttons on a panel. When one of the buttons is pressed all of the buttons should be dynamically re-created except for the button that was pressed. In other words, just hide the button that the user presses and show the other two.
For your solution to be helpful you can't statically create the buttons and then use the Visible property (or drastically change the example in other ways) - you have to re-create all the button controls dynamically upon every PostBack (not necessarily in the event-handler though). This is not a trick-question - I really don't know how to do this. Thank you very much for your effort. Here is my short example:
From the Default.aspx file:
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="ButtonsPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
From the Default.aspx.cs code-behind file:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicControls
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
AddButtons();
}
protected void AddButtons()
{
var lastClick = (string) Session["ClickedButton"] ?? "";
ButtonsPanel.Controls.Clear();
if (!lastClick.Equals("1")) AddButtonControl("1");
if (!lastClick.Equals("2")) AddButtonControl("2");
if (!lastClick.Equals("3")) AddButtonControl("3");
}
protected void AddButtonControl(String id)
{
var button = new Button {Text = id};
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Session["ClickedButton"] = ((Button) sender).Text;
AddButtons();
}
}
}
My example shows the three buttons and when I click one of the buttons, the pressed button gets hidden. Seems to work; but after this first click, I have to click each button TWICE for it to get hidden. !?
I think that you have to provide the same ID for your buttons every time you add them like this for example (in first line of AddButtonControl method):
var button = new Button { Text = id , ID = id };
EDIT - My solution without using session:
public partial class _Default : Page
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
AddButtons();
}
protected void AddButtons()
{
AddButtonControl("btn1", "1");
AddButtonControl("btn2", "2");
AddButtonControl("btn3", "3");
}
protected void AddButtonControl(string id, string text)
{
var button = new Button { Text = text, ID = id };
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
foreach (Control control in ButtonsPanel.Controls)
control.Visible = !control.Equals(sender);
}
}
You need to make sure that your dynamic controls are being added during the Pre_Init event.
See here for the ASP.NET Page Lifecycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx
When adding events you need to do it no later than the Page_Load method and they need to be added every single request, ie you should never wrap event assignment in a !IsPostBack.
You need to create dynamic controls ever single request as well. ViewState will not handle the recreation on your behalf.
One thing I notice is that when you click a button you are invoking AddButtons() twice, once in the Page_Load() and once in the button_Click() method. You should probably wrap the one in Page_Load() in an if (!IsPostBack) block.
if (!IsPostBack)
{
AddButtons();
}
AFAIK, creating of controls should not be placed in Page_Load but in Page_PreInit (ViewState and SessionState is loaded before Page_Load but after Page_PreInit).
With your problem, I would suggest to debug the AddButtons function to find out what exactly (and when) is stored in Session["ClickedButton"]. Then, you should be able to figure out the problem.
the controls that are added dynamically are not cached so this migth me one of your problems