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());" />
Related
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 ?
I've got this button
<asp:Button runat="server" ID="btnReviewDocs" CssClass="btnReviewDocs" data-theme="b"
Text="Review Documents" OnClick="btnReviewDocs_Click" OnClientClick="clickHyperlink();"/>
And in 'OnClick' event I'm assembling an URL that I need to set to asp:Hyperlink and at the end of the 'OnClick' I'm setting this URL to the 'NavigateURL' propery of the 'asp:Hyperlink'. Once the 'asp:Hyperlink' has the correct URL I need to call the 'clickHyperlink()' function.
function clickHyperlink() {
var href = $('#hlnkID').attr('href');
if (typeof href !== "undefined") {
$.mobile.showPageLoadingMsg();
window.location.href = href;
}
}
But the 'OnClientClick' event is executed always before the 'OnClick'. Any suggestions for a workaround?
I'm doing all this stuff, because I've got problems with JQuery Mobile and 'Response.Redirect(url);' is changing the page, but not the URL.
I believe that you don't really need to involve the Hyperlink control in the JS part.
Modify your JS function and remove the OnClientClick attribute from the btnReviewDocs button:
<script type="text/javascript">
function clickHyperlink(href) {
$.mobile.showPageLoadingMsg();
window.location.href = href;
}
</script>
On the server, in the btnReviewDocs_Click method:
protected void btnReviewDocs_Click(object sender, EventArgs e)
{
// TODO: set the url, maybe append some params to the
// hlnkID.NavigateUrl value
var url = "http://stackoverflow.com/";
ClientScript.RegisterStartupScript(Page.GetType(),
"clickHyperlink",
"clickHyperlink('" + url + "');",
true);
}
Use the RegisterStartupScript in the ClientScript object to run the code after postback--->
protected void btn_Click(object sender, EventArgs e)
{
//some code
this.ClientScript.RegisterStartupScript(this.GetType(), "clintClick", "clickHyperlink", true);
}
try this
protected void btnReviewDocs_Click(object sender, EventArgs e)
{
//something doing here
Page.ClientScript.RegisterStartupScript(this.GetType(), "test", "<script type='text/javascript'>clickHyperlink()</script>");//call javascript function
}
The answer is mentioned by #Alex Filipovici.
But first you should ask yourself do you really need to go back to the client side to do a redirect ?
Why not call :
Response.Redirect("MyURL");
How to get input from user using a confirm box in asp.net and store the input in a C# variable.
as whether it is a ok or cancel button. pls help me forward.
For Example i am using like this,
Response.Write("confirm('Testing FiileAlready existing Replace it?')");
instead i need the output of the confirm box in c# variable...
Try this:
Your javascript function:
<script type="text/javascript" language="javascript">
function ConfirmOnReplace() {
if (confirm("Are you sure?") == true)
return true;
else
return false;
}
</script>
The ASP.NET button:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return ConfirmOnReplace();" />
And the code-behind(YourPage.aspx.cs) file:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button1.Click += new EventHandler(Button1_Click);
}
void Button1_Click(object sender, EventArgs e)
{
// If you are here, your javascript method returned true
// TODO: Replace the file, or do what you want
}
}
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
i am having trouble catching errors in an AJAX panel. Even when i throw an exception in the c# code behind the front end completely ignores it.
Here is the code i have setup, can anyone see why?
I ideally want to show a js alert window on error.
Code Behind:
protected void btnX_Click(object sender, EventArgs e)
{
throw new ApplicationException("test");
}
protected void ScriptManager_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
ScriptManager.AsyncPostBackErrorMessage = e.Exception.Message;
}
Markup:
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, e)
{
window.alert(e.get_error().name);
}
</script>
<asp:ScriptManager ID="ScriptManager" runat="server" AllowCustomErrorsRedirect="true" OnAsyncPostBackError="ScriptManager_AsyncPostBackError" />
I think you should be displaying the 'message' error property and not 'name'
see http://msdn.microsoft.com/en-us/library/bb383810.aspx
function EndRequestHandler(sender, e)
{
if (e.get_error() != undefined)
{
var errorMessage = e.get_error().message;
e.set_errorHandled(true);
alert(errorMessage)
}
}