I have a textbox and a dropdownlist. The textbox is defaulted to 1 but if the user enters a different value into the textbox they must select a value from the dropdownlist. If they do not select a value from the dropdownlist then the exception message appears, and the changes they made to the textbox will not be saved. The problem is the value in the textbox is still there when I reopen the page. If I manually refresh the page, then it defaults back to 1. So I am trying to refresh the page after the exception message appears, but if I put code to refresh the page after the exception then the message doesn't appear anymore.
How can I refresh the page after the user closes the exception message?
JobPieceSerialNo SerNo = new JobPieceSerialNo(job.ID);
if (SerNo.Reason == null)
{
throw new Exception("Must select reason");
}
catch (Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "Message",
"<script>$(document).ready(function () { $(\"<div>" + "Please note : " + ex.Message + "</div>\").dialog({modal: true,title: \"NOTE\",buttons: [ { text: \"Ok\", click: function() { $( this ).dialog( \"close\" ); } } ]}); ShowHidePointToPoint('OVERNIGHT');});</script>");
Response.Redirect("Job.aspx?JobID=" + Request.QueryString["JobID"], false);
}
You almost certainly don't want to be throwing an Exception here, it looks like you're using an exception to handle normal UI validation and if so that's quite unusual.
There are some pretty standard ways of validating user input and presenting validation results back to the user, this article describes simple c# validation which seems to fit your problem better than throwing and catching an Exception.
You can use windows.location after closing dialog
your catch would be like this:
catch (Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "Message",
"<script>$(document).ready(function () { $(\"<div>" + "Please note : " + ex.Message + "</div>\").dialog({modal: true,title: \"NOTE\",buttons: [ { text: \"Ok\", click: function() { $( this ).dialog( \"close\" ); window.location.href = 'Default.aspx'; } } ]}); ShowHidePointToPoint('OVERNIGHT');});</script>");
}
or you can also change the window location to the current page in close function of your dialog.
JQuery UI dialog have a close event:
$( ".selector" ).dialog({
close: function( event, ui ) {window.location.href ="Job.aspx";}
});
Related
I have two near identical forms on the site and only one of them works. On firing button click they're supposed to collect text from checkbox fields and email that information on. One of the forms try is completely ignored and the error message in catch is displayed
Using the working form on the new page still won't work makes me think there may be issues with the page, but deleting the aspx and aspx.cs pages and rewriting them when it may not be that serious is not something I want to do if it's not necessary. I've tried removing 'if (IsPostBack)' and 'if (LiabilityCheckBox.Checked == true)' on the form with issues among other things, but nothing seems to help.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (LiabilityCheckBox.Checked == true)
{
// validate the Captcha to check we're not dealing with a bot
bool isHuman = ExampleCaptcha.Validate(CaptchaCodeTextBox.Text);
CaptchaCodeTextBox.Text = null; // clear previous user input
if (!isHuman)
{
lblCaptchaError.Visible = true;
lblCaptchaError.Text = "Incorrect Code. Please try again!";
}
else
{
try
{
//some code
lblRegMessage.Text =
("Registration Successful. Thank you for entering."
+ "Please click button below to finalise Payment and Registration.");
// Clear the textbox values
//Show Continue Button.
ContinueButton.Visible = true;
}
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
}
}
else
{
lblMessage.Text = ("You must check the Liability check box to continue");
}
}
}
I am expecting the result of filling out the form to be the mail is sent and a message appears telling the user "Registration Successful. Thank you for entering."
What I am getting is this:
catch (Exception ex)
{
lblMessage.Text = ("Your registration failed to send, please try again");
}
As I checked, your code missing some closing brackets. Please check the brackets are properly closed and in the series.
i m opening an Webpage(Clock.aspx) from window.showModalDialog of javascript.In the Clock.aspx i have a button and i want that when the user click on that button the Clock.aspx page will be closed. I dont want to use onClientClick() method of javascript as some server side database insertion is going on and after the insertion i want to close this page.
The Code behind of the button is as follows:-
protected void btnStop_Click(object sender, EventArgs e)
{
_nonProduction = new NonProduction();
if (Session["LastNonProdTimeID"] == null)
{
}
else
{
int NonProdTimeEntryID = Convert.ToInt32(Session["LastNonProdTimeID"]);
//Updating the TimeSpent
isTimeSpentUpdated = _nonProduction.UpdateTimeSpentInDB(NonProdTimeEntryID);
if (isTimeSpentUpdated == true)
{
string timespent = Convert.ToString(_nonProduction.GetTimeSpent(NonProdTimeEntryID));
string msg = "Total time consumed in " +HiddenTaskname.Value.ToString()+": " + timespent.ToString() + " Minutes";
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
//ShowPopUpMsg(msg);
}
else
{
}
}
}
Here when i m clicking on the Button one more (Clock.aspx)pop up is appearing and window is not closing. Please help me that how i close the ShowModalDialog from server side code. I m using Script manager in my page also.
Thanks in Advance.
I had added <base target="_self">to the head section of the clock.aspx page and then it works fine for me.
For mine, I have a function in normal javascript that closes the page in the aspx.
In the code behind, if the update is successful, it calls that function.
// this function is to be called by the popup windows to refresh the opener using specific office code, and close self
function allDoneOffice(office)
{
var opener = self.opener;
if (opener.doRefresh) opener.doRefreshWithOfficeCode(office);
window.open('','_self',''); // IE warning hack
self.close();
}
// update the record
bool b = report.SaveModifiedToDB();
if (b)
{
// don't close the page if nothing was updated
ClientScript.RegisterStartupScript(this.GetType(), "load", "<script type=\"text/javascript\">\n" +
"allDoneOffice('" + report.OfficeCode + "');" + "<" + "/script>");
}
else
{
lblResults.Text += " Unable to save modified report to the database.";
}
Use this code below should work in IE
Response.Write("<script language='javascript'> { self.close() }</script>");
I have a code block that leads to a "Internet Explorer cannot display the webpage" error. When I click the submit button, with NONE of the radio buttons checked, the web page status bar displays "waiting for response from host" and then display the "Internet Explorer cannot display the webpage". When I walk through the code in visual studio, the code executes fine, and none of the catch blocks are executed.
How can I trap the error and determine why the error page is being displayed?
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (rbtnSearchBy1.Checked)
{
Server.Transfer("ViewEmpHistory.aspx");
}
if (rbtnSearchBy2.Checked)
{
Server.Transfer("SearchEmp.aspx");
}
if (rbtnSearchBy3.Checked)
{
Server.Transfer("ViewEmpCard.aspx");
}
}
catch (ThreadAbortException)
{
throw;
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Whatever .cs page your "btnSubmit_Click" is on, put a breakpoint on that page_load event.
Also, put a breakpoint on the page_load event of "ViewEmpHistory.aspx", "SearchEmp.aspx" & "ViewEmpCard.aspx". (so now you have four breakpoints).
Step through the project again and make sure all parameter values are being passed correctly, also make sure that you have correct logic (if applicable) for If (!PostbacK) conditions etc.
HTH
if you don't select one radiobutton it's normal that you don't enter in your catch , because your application no throw exception.
but you can view your eventlog
Enter in your cmd : eventvwr to access your event log
To debug these kind of issues, I often find it easier to use Tracing.
You can turn on tracing at the application level, or at the page level.
Your method call will then become:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (rbtnSearchBy1.Checked)
{
Server.Transfer("ViewEmpHistory.aspx");
}
if (rbtnSearchBy2.Checked)
{
Server.Transfer("SearchEmp.aspx");
}
if (rbtnSearchBy3.Checked)
{
Server.Transfer("ViewEmpCard.aspx");
}
}
catch(Exception ex)
{
Trace.Warn("Exception Caught", "Exception: btnSubmit_Click", ex);
}
}
You can look at the trace log by then navigating to the Trace Viewer.
What you've done is not exactly well structured. It's cleaner if the blocks are exclusive - which is why I've added the else statements to the code below. I've also indicated where you would want to handle the state where no button is checked in comments.
But you're right, there isn't any exception being thrown. Your code didn't throw one, and when you end processing a request without returning any type of response it doesn't cause an exception.
if (rbtnSearchBy1.Checked)
{
Server.Transfer("ViewEmpHistory.aspx");
}
else if (rbtnSearchBy2.Checked)
{
Server.Transfer("SearchEmp.aspx");
}
else if (rbtnSearchBy3.Checked)
{
Server.Transfer("ViewEmpCard.aspx");
}
else
{
// Here's where the logic will flow to if no radio button is clicked.
// We could
// * Server.Transfer to a default location
// * Throw an exception
// * Do nothing, which returns no response, and causes
// IE to complain that it could not display the webpage.
}
I have a problem with this that works for one button and not for another.
The one that works is a button that calls a ModalPopup to add a new row to a GridView inside an UpdatePanel. If it's successful, it pops up an alert with a message, else another alert with the Exception message. The code is very similar to the other one's, except it's in a ModalPopupExtender.
The button that throws the known exception about the EventValidation goes as follow:
Web:
<asp:Button ID="btnAlquilar" runat="server" Text="Alquilar" CssClass="AdminButtons"
OnClientClick="Click_Alquilar(); return false"/>
The JavaScript function it calls
function Click_Alquilar() {
if (index == '') {
alert("Debe elegir una película para alquilar");
}
else {
if (confirm("¿Quiere alquilar la película '" + selected.childNodes[2].innerText + "'?")) {
__doPostBack('<%= btnAlquilar.UniqueID %>', index);
}
}
}
Where index is the index of the selected row in the GridView (done with a similar architecture, and works fine).
The code-behind starts in the Page_Load method, and calls the function I'm having trouble with:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{...}
else
{
ProcessAjaxPostBack(sender, e);
}
}
private void ProcessAjaxPostBack(object sender, EventArgs e)
{
if ((Request.Params["__EVENTTARGET"] != null) && (Request.Params["__EVENTARGUMENT"] != null))
{
...
if (Request.Params["__EVENTTARGET"] == this.btnAlquilar.UniqueID)
{
index = Convert.ToInt32(Request.Params.Get("__EVENTARGUMENT").TrimStart('r', 'o', 'w'));
btnAlquilar_Click(Request.Params.Get("__EVENTARGUMENT"));
}
}
}
protected void btnAlquilar_Click(string id)
{
string message = "";
if (BAC.BAC.CheckUserAge(lblUserId.Text) < Convert.ToInt32(dgvPeliculas.Rows[index].Cells[7].Text))
{
btnBorrar.Visible = false;
btnEditar.Visible = false;
btnNuevo.Visible = false;
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No tiene la edad mínima para alquilar la película.')", true);
}
else
{
try
{
BAC.BAC.NewAlquiler(lblUserId.Text, dgvPeliculas.Rows[index].Cells[0].Text, dgvPeliculas.Rows[index].Cells[9].Text);
}
catch (Exception ex)
{
message = Change_ExceptionMessage(ex.Message);
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No se pudo alquilar la película: " + message + "')", true);
}
}
}
The RegisterClientScriptBlock method is THE SAME I use for the other button (which doesn't do anything more complex than this one: if things are wrong, it changes the text of a label in the Popup and shows the alert; if it's right, it loads the GridView and shows the success alert), and works there. Here, it throws the exception "EnableEventValidation is true so...". I have this button registered for Event Validation on Render:
protected override void Render(HtmlTextWriter writer)
{
this.Page.ClientScript.RegisterForEventValidation(btnAlquilar.UniqueID);
base.Render(writer);
}
So why does this happen here? Why it doesn't work this time?
EDIT: Now that I check, the label changed by the working button in the ModalPopup is wrapped in an UpdatePanel. I don't know if it matters, but just to note it.
EDIT2: The page also works within a Master page. Don't know if it's of any use. I have tried wrapping both the Edit button and the GridView with UpdatePanels and using AsyncPostBackTrigger, but still I get the same exception.
OnClientClick="Click_Alquilar(); return false"
instead of this use
OnClientClick="return Click_Alquilar();
and in javascript
use return false;
in functions like
function Click_Alquilar() {
if (index == '') {
alert("Debe elegir una película para alquilar");
return false;
}
else {
if (confirm("¿Quiere alquilar la película '" + selected.childNodes[2].innerText + "'?")) {
__doPostBack('<%= btnAlquilar.UniqueID %>', index);
}
}
}
OK, for those who are interested in it, the problem was with the _doPostBack calls. Since the arguments I passed (_EVENTARGUMENT) were dynamic, I could never register those events through the RegisterForEventValidation method, becuase it asks for two constant strings (AFAIK): the control's UniqueID and the argument it will be passed with it.
So, I stopped passing arguments to the doPostBack other than the button's UniqueID, and passed the variables I was interested in through other media (cheifly, hidden fields values to global variables inside the Page class).
That solved the problem and made the program work as intended. I wrapped the buttons inside the same update panel than the GridView so as to not generate an AutoPostBack and change the Grid's values without having to refresh.
If anybody is interested in the code, I can provide.
I have my own exception based on some condition and want to raise an alert when control comes in this catch block
catch (ApplicationException ex)
{
//want to call window.alert function here
}
Do you mean, a message box?
MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx
It's a bit hard to give a definitive answer without a bit more information, but one usual way is to register a startup script:
try
{
...
}
catch(ApplicationException ex){
Page.ClientScript.RegisterStartupScript(this.GetType(),"ErrorAlert","alert('Some text here - maybe ex.Message');",true);
}
if you are using ajax in your page that require script manager Page.ClientScript
will not work,
Try this and it would do the work:
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"alertMessage", #"alert('your Message ')", true);
You can use the following extension method from any web page or nested user control:
static class Extensions
{
public static void ShowAlert(this Control control, string message)
{
if (!control.Page.ClientScript.IsClientScriptBlockRegistered("PopupScript"))
{
var script = String.Format("<script type='text/javascript' language='javascript'>alert('{0}')</script>", message);
control.Page.ClientScript.RegisterClientScriptBlock(control.Page.GetType(), "PopupScript", script);
}
}
}
like this:
class YourPage : Page
{
private void YourMethod()
{
try
{
// do stuff
}
catch(Exception ex)
{
this.ShowAlert(ex.Message);
}
}
}
You can also do this :
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showError",
"alert('" + ex.Message + "');", true);
}
this will show the exeption message in the alert box
MessageBox like others said, or RegisterClientScriptBlock if you want something more arbitrary, but your use case is extremely dubious. Merely displaying exceptions is not something you want to do in production code - you don't want to expose that detail publicly and you do want to record it with proper logging privately.
I'm not sure if I understand but I'm guessing that you're trying to show a MessageBox from ASP.Net?
If so, this code project article might be helpful: Simple MessageBox functionality in ASP.NET
Simple use this to show the alert message box in code behind.
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Record Saved Sucessfully');", true);
You can try this:
Hope it works for you..
`private void validateUserEntry()
{
// Checks the value of the text.
if(serverName.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = "You did not enter a server name. Cancel this operation?";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}`
You should try this.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Sakla Test');", true);