Using C# with ASP.NET, how do I show a "success" message when my user submits a form? And at the same time say "The image has successfully saved", with a link, so that the image created can be viewed by clicking the link?
Wrap your form in an <asp:Panel> and create another <asp:Panel> with Visible="False" for your Thank you message. Once the form is submitted, change the visibility of each panel, setting the form to Visible="False", and the thank you message panel to Visible="True".
Hope that makes sense, here's an example:
<asp:Panel ID="pnlFormFields" runat="server">
... form fields here ...
</asp:Panel>
<asp:Panel ID="pnlThankYouMessage" runat="server" Visible="False">
... Thank you message here ...
</asp:Panel>
Then inside your codebehind
protected void btnSubmit_Click(object sender, EventArgs e) {
// Hook up uploaded image and assign link to it
pnlFormFields.Visible = false;
pnlThankYouMessage.Visible = true;
}
If you need label to display message. Add a label on the page and set its attribute visible = false in aspx and use the code below:
protected void btnSubmit_Click(object sender, EventArgs e) {
if(SaveRecordsToDataDatabase())
{
If(UploadImage())
{
showMessage("Save successfull",true);
}
else
{
showMessage("Save failed",false);
}
}
else
{
showMessage("Save failed",false);
}
}
private bool UploadImage()
{
// you upload image code..
}
private bool SaveRecordsToDatabase()
{
// db save code
}
private void showMessage(string message, bool success)
{
lblMsg.visible = true; // here lblMsg is asp label control on your aspx page.
lblMsg.FontBold = true;
if(success)
lblMsg.ForeColor = Color.Green;
else
lblMsg.ForeColor = Color.Green;
lblMsg.Text = message;
}
For consistency you can use Transaction in above code so as to prevent save operation if image upload fails. Otherwise its your choice. The new code with Transaction will be , given below:
protected void btnSubmit_Click(object sender, EventArgs e) {
using(TransactionScope scope = new TransactionScope())
{
if(SaveRecordsToDataDatabase())
{
If(UploadImage())
{
showMessage("Save successfull",true);
}
else
{
showMessage("Save failed",false);
}
}
else
{
showMessage("Save failed",false);
}
}
scope.complete()
}
Here to refer transaction scope, add reference System.Transactions.
İf you want to show message on client side controls, like alert("saccess");
you can use ajax and webmethod in Why doesn't my jQuery code work in Firefox and Chrome?
if you want to show message on server side you can use panel, label or div (runat server and have id) and default setting of them, set visiible false, when you show message you can set visible true via code behind..
use a label(visible=false) and a hyperlink from the toolbox .when u upload an image u must be inserting the url of savefile location to a database.so when that insert query is fired that will return an integer value which is d no of lines inserted in db.compare it like if that value > 0 then set visibily of label to true and label.text="success" finally set the navigate url of the hyperlink to d url of saved image which can be used to creat a view link of the image
Related
using asp.net | C#
I want my ImageButton to open a URL when I click it. I finally have my Image loading and it clicks but when I click it nothing happens. Here is the code I have so far:
aspx page
<asp:ImageButton ID="Button1" runat="server" ImageUrl="~/images/button.gif"
onclick="Open_Click"></asp:ImageButton>
aspx.cs page
protected void Open_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
try
{
System.Diagnostics.Process.Start("http://www.website.com");
}
catch { }
}
You want to do a redirect, not start a process. Try this:
protected void Open_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
try
{
Response.Redirect("http://www.website.com");
}
catch { }
}
Additionally, you could just set the PostBackUrl attribute on the control and have no need for a server side event.
You can do it on the client-side:
This will open in another window:
<asp:ImageButton OnClientClick="window.open('/xxx/xxx.aspx');
OR this will open in same window, javascript needs to return false so server code won't run:
<script>
function ReDirect() {
location.href = '/xxx/xxx.aspx';
return false;
}
</script>
asp:ImageButton OnClientClick="javascript:return(ReDirect());" />
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 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.
Am using the below message box in asp.net web application. Now i want to convert this message box as a confirmation message box and do something when it is true else means reject the application.
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('Are you sure, you want to apply?');</script>", false);
I think you are going about this the wrong way. You should display this confirmation before posting back, and then only post back if they choose to "Apply".
Using ASP.NET web controls, the Button control has an OnClientClick property which can be used to call javascript prior to Http POST:
You could do something like this:
<asp:button id="btn"
runat="server"
Text="Apply"
OnClientClick="return confirm('Are you sure you wish to apply?');"
OnClick="btn_Click" />
register script bellow instead of alert
<script type="text/javascript">
var r=confirm("Are you sure you are sure?")
if (r==true)
{
//You pressed OK!
}
else
{
//You pressed Cancel!
}
</script>
The javascript equivalent to a confirmation box is the confirm() method. This method returns a true or false value depending on the user's "OK" or "Cancel" button response.
Usage:
var confirmed = confirm('Are you sure?','Are you sure you want to delete this item?');
if(confirmed){
//do something
} else {
//do something else
}
Try this
Add this on your cs file to display a confirm instead of alert
string confirm =
"if(confirm('Are you surely want to do this ??')) __doPostBack('', 'confirmed');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", confirm, true);
Add this on same page to check when user is coming from that confirmation box
protected void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (string.Equals("confirmed",
parameter,
StringComparison.InvariantCultureIgnoreCase))
{
// Call your server side method here
}
}
For this I used __doPostBack you can learn more about it from here.
Hope it'll help you
private void showMessage(string msg){
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "<script language='javascript'>alert('"+ msg +"');</script>", false);
protected void BtnReg_Click(object sender, EventArgs e)
{
OracleHelper.OracleDBOpen();
object flag = OracleHelper.OracleExecuteScalar("your select Query ");
if (flag == null)
{
showMessage("Failed !!! ");
}
else
{
string reg = String.Format("your Insert Query ");
showMessage("successfuly");
OracleHelper.OracleExecuteNonQuery(reg);
}
OracleHelper.OracleDBClose();
}
}
To do this completely within C#, you can try this:
protected override void OnInit(EventArgs e)
{
AddConfirmationButton();
base.OnInit(e);
}
private void AddConfirmationButton()
{
Button confirmButton = new Button();
confirmButton.Text = "Action Foo";
string confirmationMessage = "Are you sure you wish to do action Foo?";
confirmButton.OnClientClick = "return confirm('" + confirmationMessage + "');";
confirmButton.Command += confirmButton_Command;
Controls.Add(confirmButton);
}
void confirmationMessage_Command(object sender, CommandEventArgs e)
{
DoActionFoo(); //work your magic here.
}
This presents and "OK/Cancel" dialog box to the user from the webpage. If the user clicks 'ok', the function from the command Event fires. If the user clicks 'cancel', nothing happens.
ScriptManager.RegisterStartupScript(page,this.GetType(), "temp","javascript:calopen();
",true);
function calopen()
{
if (confirm("Are you sure?"+'\n'+"Are you want to delete"))
{
enter code here
}
else
{
return false;
}
}
try this code check on OnClientClick event when user click on button
<script type="text/javascript">
function check()
{
var chk =confirm("Are you sure you are sure?")
if (chk==true)
{
// try you want
}
else
{
// try you do not want
}
return true;
}
</script>
<asp:button id="Button1"
runat="server"
Text="Button1"
OnClientClick="return check();"/>
hi i need to modify my code a little bit. i have a page with a radio button list and a textarea. the textarea is populated when a users makes a radio button selection.
also, when a user makes a radio button selection the url will hold an extention in the url to show which selection index number they have selection. (i.e. ?selected=0)
http://test.com/frm_Articles.aspx?selected=0
http://test.com/frm_Articles.aspx?selected=1
http://test.com/frm_Articles.aspx?selected=2
that way they can copy the url and reference it in other websites as a link. or place it in their favorites.
the problem is, if you grab the url and open a new browser, the page does not pass the value and databind accordingly. no radio buttons or content appear on the page.
must be the postback logic i think???
what's working:
when i launch the website the radio buttons appear and index 0 is set
when i select radio buttons the correct data displays and urls linking to radio button values display in browser (i.e. http://test.com/test.aspx?selected=2)
if i cut and paste pointer urls within the same browser then correct data is rendered
what doesn't work (everything that deal with an false PostBack):
1.when i launch website no data within the textarea apprears even though the radio button is set to 0 index and is visiable.
2. if i cut and paste pointer url into a new browser, text area and radio buttons do not display.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int selected;
if (Request.QueryString["selected"] != null)
{
if (int.TryParse(Request.QueryString["selected"], out selected))
{
RadioButtonList1.SelectedIndex = selected;
RadioButtonList1.DataBind();
}
}
else
{
int firstart = 0;
RadioButtonList1.SelectedIndex = firstart;
RadioButtonList1.DataBind();
}
}
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
//
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
try{
e.Command.Parameters["#URL_FK"].Value = Session["URL_PK"];
}
catch (Exception ex)
{
}
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strRedirect;
strRedirect = "test.aspx?selected=" + RadioButtonList1.SelectedIndex;
Response.Redirect(strRedirect);
}
}
In your code at Page_Load event before this line
RadioButtonList1.SelectedIndex = selected;
you should bind RadioButtonList1. after binding RadioButtonList you can set SelectedIndex.
my SqlDataSource1_Selecting method was the issue. i used another approach and my code worked.