I am using MessageBox class in Asp.NET with C# by imposing the namespace
using System.Windows.Forms
I have the following code:
/* Method for displaying the Message Box */
public void MsgBox()
{
string message = "Do you want to modify the rate list?";
string caption = "";
MessageBoxButtons buttons = MessageBoxButtons.YesNoCancel;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes) {
Response.Redirect("PaperRateList.aspx");
}
}
/*Calling of the above method in the following event */
protected void Save_Click(object sender, EventArgs e)
{
CompanyMaster_Insert();
RateList_Save();
MsgBox(); /*method*/
}
Now the problem is that the message box is appearing behind the form in minimized mode.and the form can be closed before closing the message bos.I want this messagebox on the form and i want to close the form after closing the message box.
MessageBox in web environment is not the best path to go, as it's a cheap way of implementing a windows form feature.
You have 2 ways to do this, server side (if you need to process some data) or client side (if you have all the data in the page and you can process it using javascript).
For you particulary example, you probably have a submit button like:
<asp:Button id="btnSave" runat="server"
onclick="btnSave_Click" text="Save Form" />
try to add this:
onclientclick="return confirm('Do you want to modify the rate list?');"
so it ends up like:
<asp:Button id="btnSave" runat="server"
onclick="btnSave_Click" text="Save Form"
onclientclick="return confirm('Do you want to modify the rate list?');" />
That's just using a javascript method called confirm.
To make nice MessageBox examples, and to avoid the user not to mess up with the page while the message is visible, it's called Modal Dialog or Modal Window, try to search for it...
jQuery UI has a Modal element that you can use, and if you fancy AJax stuff and you're a beginner in ASP.NET, I strongly suggest you to try the ASP.NET Control Toolkit
try
WebMsgBox class represents a message box for ASP.NET applications. This class has a static method Show, which is used to display a message box. The Show method takes a single argument of string type, which is the message you want to display.
private void Page_Load( object sender, System.EventArgs e )
{
MessageBox.Show( "Hello World!" );
MessageBox.Show( "This is my second message." );
MessageBox.Show( "Alerts couldnt be simpler." );
}
You can use ModalPopupExtender of AJAXControlToolkit:
ModalPopup Example
Related
I'm having an issue with the cycle of a page reload and I can't figure it out. I have an ASP button the runs at the server but it has an associated client side click. The client side Javascript is running correctly and returning true to the button click so it is also running. The Javascript makes a modification to the query string on the URL and this is also working. However, in the C# code behind, the query string is not there. Somewhere, I'm missing something.
The HTML link:
<asp:Button ID="btnRunMOReport" class="button-dbg" runat="server"
Text="Run MO Report" OnClick="btnMO_Report_Click"
OnClientClick="return validateCheckBoxesMO()" />
The JavaScript portion:
function validateCheckBoxesMO() {
token='xyz';
let url1 = window.location.href;
if (url1.indexOf("?") > 0) {
url1 = url1.substring(0, url.indexOf("?"));
}
url1 += "?hiddenToken=" + token;
window.location.replace(url1);
return true;
}
The hiddenToken is now represented on the page (?hiddenToken=xyz).
The code behind:
protected void btnMO_Report_Click(object sender, EventArgs e)
{
MailMessage mailtest = new MailMessage();
mailtest.IsBodyHtml = true;
SmtpClient SmtpServertest = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]);
mailtest.To.Add("Whoever#test123.com");
mailtest.From = new MailAddress("Whoever#test123.com");
mailtest.Subject = Request.QueryString["hiddenToken"];
mailtest.Body = "Whatever";
}
The mail comes just fine but the subject is blank. Somehow, during the page reload cycle, the query string has not yet been set.
If there is a better way to pass data from the JavaScript to the code behind, I'm all ears.
I want to launch another page from the code behind but I need some data that is returned from the JS. The token is actually something I fetch, process the JSON and now I want to make that token available to the code behind for additional information to add to the new URL I am constructing. Probably TMI for this but it is what I am trying to do.
Thanks for your assistance.
Your script isn't working because the browser makes a POST request to submit the form (and __VIEWSTATE) using the action="" attribute of the <form> that WebForms adds to your page.
When your client-script sets window.location it isn't changing how the <form> will behave. You could use your script to append the new querystring value to the <form>'s action="" attribute and this may work, however it will likely fail if the application has request-validation enabled (in which case ASP.NET will reject a tampered form submission).
As you're using WebForms (and you shouldn't be using WebForms in 2021...) you shouldn't try to fight it unless you understand how it all works (I'm not trying to be condescending: it took me years to figure it all out and I've been using WebForms since 2004).
Instead, provide the value through an <asp:HiddenField>:
Change your .aspx markup to this:
<asp:Button runat="server" ID="btnRunMOReport" class="button-dbg"
Text="Run MO Report" OnClick="btnMO_Report_Click"
OnClientClick="return validateCheckBoxesMO()" />
<asp:HiddenField runat="server" ID="superSecretHiddenField" />
Change your client script to this:
function validateCheckBoxesMO() {
const hiddenFieldId = '<%= this.superSecretHiddenField.ClientID %>';
const hiddenField = document.getElementById( hiddenFieldId );
token='xyz';
hiddenField.value = token;
return true; // <-- This is wrong, btw. Instead use `Event.prototype.stopPropagation()` - but that requires the on-click function to be wired-up correctly and I don't remember the specifics other than that WebForms *doesn't* do things correctly (not out-of-spite, but because WebForms predates the standardisation of client-script events).
}
And your code-behind to this:
protected void btnMO_Report_Click(object sender, EventArgs e)
{
MailMessage mailtest = new MailMessage();
mailtest.IsBodyHtml = true;
SmtpClient SmtpServertest = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]);
mailtest.To.Add("Whoever#test123.com");
mailtest.From = new MailAddress("Whoever#test123.com");
mailtest.Subject = this.superSecretHiddenField.Value;
mailtest.Body = "Whatever";
}
As noted, a button post back will in general over-write the url that you change. Unless you actually do a navigation client side that is caused by the js, then it will not persist.
So, on the most simple level, just drop in a text box, or hidden field, and put the value you need/want into that hidden textbox or field.
So, client side? Markup?
You can use this:
<asp:Button ID="Button1" runat="server" Text="Delete"
OnClientClick="SetHidden();"/>
<asp:HiddenField ID="HiddenField1" runat="server" ClientIDMode="Static"/>
<br />
<script>
function SetHidden() {
hField = document.getElementById('HiddenField1');
hField.value = 'zoo';
return true;
}
</script>
So in above, we set our value in js to zoo, and of course we do return true. If we return false then the asp.net button code server side will not run - so we can control this, or even say pop up a confirm dialog and return true/false based on that to control if the server side code behind will run.
Server side, code behind? You can now use this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Debug.Print(HiddenField1.Value)
End Sub
So the above is easy, clean. You can also use a text box, and set the style="display:none", but a hidden field is just as well and easy.
Clicking on ASP.NET button redirects to correct website but on the same tab, not in a new tab what i need to do. What's wrong with the code OnClientClick="aspnetForm.target ='_blank';" below? Why it is not enough alone and what else need to be done?
The following ASP.NET code for the button control is:
<asp:Button ID="btnGenerateReport" runat="server" Text="Generate Report"
OnClick="btnGenerate_Click" OnClientClick="aspnetForm.target ='_blank';" />
I know two methods for redirecting the page to new tab in asp
1) The first method which you are already using and it works also. Make an onclientclick event of Button and on code behind of Button
Click write the following code:-
button.OnClientClick = "aspnetForm.target='_blank'"; Response.Redirect("yourpage.aspx");
2)You can also use javascript
button.Attributes.Add("onclick", "window.open('yourpage.aspx');return false;");
Both the method will redirect your page to new tab on clicking the button.
The error with your code is OnClientClick = "aspnetForm.target='_blank;'" remove the semicolon after '_blank' and it will work
If you are looking out for server side code to open a new window on Button Click, then here's how to do so.
Add the following script to the section of your page
<script language="javascript" type="text/javascript">
function openNewWin(url) {
var x = window.open(url, 'mynewwin', 'width=600,height=600,toolbar=1');
x.focus();
}
</script>
Then add a Button Control in the following manner
<asp:Button ID="btnOpenPop" runat="server" Text="Open Pop"
onclick="btnOpenPop_Click" />
Finally add some code in the code behind file
protected void btnOpenPop_Click(object sender, EventArgs e)
{
string url = "http://www.dotnetcurry.com";
ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>openNewWin('" + url + "')</script>");
}
You can't use target attribute on button.
You have to use javascript function window.open()
Check this:
Window open() Method
I don't post links lightly, but I found this site explains all and it has solved my problem too.
http://dotnetspidor.blogspot.co.uk/2009/01/open-new-window-in-aspnet-web-page_28.html
I have this hyperlink called “SEND” in a ASP page called Home and here it is:
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("Post_ID", "~/RCA.aspx?Post_ID={0}") %>'
Text="SEND"></asp:HyperLink>
</ItemTemplate>
when the user clicks the hyperlink it goes to another page called RCA and in this page there is a Button and here it is the code:
<asp:Button ID="btnRCA" runat="server" onclick="Button1_Click"
Text="Assign RCA" Width="147px" />
so I want this button to be visible only when clicked the hyperlink in the HOME page. I am planning to have another button or control in the RCA page that will make it invisible when clicked or before someone leaves the page they have to make it invisible the Button by clicking some other control. can someone help me with this? thanks
Use a QueryString parameter.
Home.aspx
//When linked to RCA.aspx from Home.aspx, a parameter called ShowButton=1 is included
//in the URL.
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# Eval("Post_ID", "~/RCA.aspx?Post_ID={0}&ShowButton=1") %>'
Text="SEND"></asp:HyperLink>
RCA.aspx
//By default, since you want the button to NOT appear for all incoming traffic EXCEPT
//that which came from Home.aspx, the button's Visible property is set to false.
<asp:Button ID="btnRCA" runat="server" onclick="Button1_Click"
Text="Assign RCA" Width="147px" Visible="false" />
RCA.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//If the querystring has a parameter called ShowButton and it's equal to "1",
//then set the button to Visible = true.
//Else, do nothing, keeping the button in it's default, Visible=false state.
//By putting this in an "IsPostback == false" check, you can guarantee that this will
//only happen on first page_load, and won't be triggered again even if you do other
//actions in the page that cause Postback
//For example, if you don't use this !IsPostback check, and you end up creating some
//new function that causes the button to be hidden again, but then you make a
//selection from a dropdown list that causes postback, you will trigger the call to
//make the button Visible again, even though that's probably what you don't want at
//this point, since your other new function set it to Visible = false.
if (!IsPostback)
{
if (Request.QueryString["ShowButton"] == "1")
{
RCAbtn.Visible = true;
}
if (Request.QueryString["Post_ID"] != null)
{
//do whatever you need to with the post ID
}
}
}
SomeOtherPage.aspx.cs
Response.Redirect("RCA.aspx?Post_ID=1234"); //button will be invisible
And then let's say later that you want to re-direct from some other page and have the button be visible, like the redirect from Home:
Response.Redirect("RCA.aspx?Post_ID=1234&ShowButton=1"); //button will be visible
If you don't like cluttering up your URL or you feel that it looks tacky to have what you are doing so plainly available to the user's eyes, you don't necessarily need to use "ShowButton". You could say ?Post_ID=1234&fkai3jfkjhsadf=1, and then check your query string for "fkai3jfkjhsadf". I like to do that sometimes because then from the users point of view, it makes me look like I'm doing something really technical and encrypted, and not just passing around a bunch of basic instructions in plain English :) Downside there is you need keep track of your own query string parameters.
Edit:
If you want to get the URL with only the Post_ID and nothing else, you can do this:
string currenturl = Request.Url.ToString(); //get the current URL
string urlToSend = currenturl.Substring(0, currenturl.IndexOf("?")); //cut off the QueryString entirely
urlToSend += "?Post_ID=" + Request.QueryString["Post_ID"]; //re-append the Post_ID
Be aware that your call to Substring will cause an exception if the URL doesn't have a QueryString, so please patch that up in whatever way works best for you (try/catch, etc.).
After that, you should just be able to use the "urlToSend" string in your mailMessage.Body.
on your second page in your page_load, try this:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Post_ID"] != null)
{
btnRca.Visible = true;
}
}
I don't know how you want to handle the visibility of this button in other cases, but this should answer your particular question.
My code:
protected void btnOk_Click(object sender, EventArgs e)
{
if (txtReportFavorite.Text != string.Empty)
{
//..
}
else
{
Response.Write("<script>alert('Enter Favorite name.')</script>");
// I need to prevent page refresh here.
}
}
How can I stop refreshing the page in the else condition. Thanks.
You can't.
The new page has already been requested when that code runs. If you don't do a postback, that code will never run.
If you want to do the validation without doing the postback, you should do it using client code instead.
The fact that you got to the server side means that your page has done a full cycle to the server and refreshed itself.
Unless you are calling this code with an Ajax call.
You can also achieve this by placing an AjaxUpdatePanel around your button that will simulate an Ajax call when your clients will submit your form.
in your code behind on page load put this
btnOk.Attributes.Add("onclick","return validate();");
in your aspx file have this script
function validate()
{
if(document.getElementById("txtReportFavorite").value == "";
{
alert("Enter Favorite name");
return false;
}
}
Your page is already go to the server side and it is in already postback is progressing.
you have to use client side code for preventing postback.
why not to use RequiredFieldValidator if only empty textbox need to validate?
you can do it on client side.
<asp:TextBox runat="server" id="txtReportFavorite" />
<asp:RequiredFieldValidator runat="server" id="txtReportFavorite" controltovalidate="txtName" errormessage="Enter Favorite name!" />
<br />
<asp:Button runat="server" id="btnSubmit" text="Ok" onclick="btn_Click" />
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid) //for secure validation
{
//do something
}
}
Try using RegisterScriptBlock.
ClientScript.RegisterStartupScript(this.GetType),"","$(document).ready(function(){alert('Enter Favorite name.')});",true);
If you want to perform from server-side do it like above.. Otherwise many answers already posted.
The kind of functionality you are showing can be easily achieved by using a Validator so the page won't post back.
As once it reaches the server, its really not possible to stop the refresh. Well, at least as far as I know.
-Milind
I have an application that I am currently writing that works by iterating through nodes, and then updating the page with the information of the current node. I have an UpdatePanel in the page which contains a label, textbox, and a button. The label lists the currently available children of the current node, the user enters in which child they want to go to into the textbox, and then hits the submit button. I set the new value of the node in the submit button's event handler.
Here's my problem: Every time I enter in which node I want to navigate to, the object resets its value to the value it was initially initialized to. I have even put this same code into a Windows Form to validate that it's working correctly to iterate through my tree, and it works as it should, so I know my problem is AJAX-related.
This is the first app that I have written using AJAX, so I am still in the process of learning how it works. Any help would be greatly appreciated. I have Googled and searched SO through and through.
Here is the HTML:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="question" runat="server" Text=""></asp:Label>
<br />
<asp:TextBox ID="answer" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Submit" runat="server" Text="Submit" onclick="Submit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
And the C#:
protected void Submit_Click(object sender, EventArgs e)
{
int ans = int.Parse(answer.Text);
if (!current.ChildIDs.Contains(ans))
{
return;
}
current = tree.Node(ans);
question.Text = current.Question;
}
current is the current node, which has a public ArrayList of all of its children's IDs. tree is the NodeTree I have; calling Node just returns the new node. Both current and Tree get initialized in the Page_Load event, and that only fires once (when the page is first loaded).
It's really pretty simply code; I'm just having difficulty understanding why the AJAX isn't working correctly.
I have even put this same code into a
Windows Form to validate that it's
working correctly to iterate through
my tree, and it works as it should, so
I know my problem is AJAX-related.
It sounds like you're expecting ASP.NET to remember what the object current is between requests, since that's how Windows forms applications work.
Web applications are stateless - after each request, ASP.NET discards all your variables. To access the variable during a subsequent request, you have to either:
1) Send enough data with the request to reconstruct the variable. You can do this using a querystring parameter or an HTML form value (the hidden fields another response mentioned).
2) Save the variables in a Session store (which can be in-memory or backed by a database).
3) Store the value in a coookie.
Of these three, it's easiest to show you how to use Session, given what you've shared in your question. However, beware: session has its risks - by default, ASP.NET session objects are stored in-memory, and it's a potential security hazard. But here's how you should be able to get your application to work.
// In your Page_Load code that initializes your 'current' variable
// When the user first requests the page, create a new Node
if (! this.IsPostBack)
{
Node current = new Node(); //
Session("currentNode") = current;
}
// When the user clicks a button on the page (posts), use the
// node in session instead
else
{
current = Session("currentNode");
}
When you update non-form elements in the browser (labels, literals, etc.), .NET is unable to see any of the changes you've made.
Try adding a hidden input for each label that records the new value. Then within the method you have wired up to the button's OnClick event, do something like this:
myLabel.Text = myHiddenInput.value;
I think you just need to tell the updatepanel to update itself. Try this:
protected void Submit_Click(object sender, EventArgs e)
{
int ans = int.Parse(answer.Text);
if (!current.ChildIDs.Contains(ans))
{
return;
}
current = tree.Node(ans);
question.Text = current.Question;
UpdatePanel.Update();
}