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
Related
This has to be the simplest thing in the world but it just isn't working.
I have an outer div to which I want to apply a class to make its display style = none so that it hides all the content within it. It's actually an asp:panel element so I'm assuming I can just set control.CssClass = "my-hidden-class" in the code behind.
I'm actually setting this on a button click handler(depending on certain conditions) But the class is never applied. When I inspect the div element in Firebug it doesn't even have a class attribute. It appears exactly as it is in the .aspx markup (the actual css class is fine & gets applied when I add it declaratively).
Also, I can see the class applied if I set CssClass in the prerender method on the initial get request. So I thought maybe I'll put all the logic in prerender and update the Css Class accordingly. This also doesn't work - the class gets applied on the initial get ok but I can't change it subsequently.
So, to sum up it seems I can't apply class from code behind at all in the event handler and I can only apply it in prerender for the intial get request & this value is persisted on all postbacks.
What am I doing wrong?
Edit: Here's the code -
aspx:
<asp:panel runat="server" ID="TariffContainer"><!--this is the div I want to toggle-->
<cms:ContentBlock ID="currentTariffsInfo" SkinID="Public/OurPrices/CurrentTariffsInfo" runat="server" />
<ucTcrPanel:tcrpanel ID="tcrpanel" PagingEnabled="true" runat="server" />
<div class="quick-price">
<asp:LinkButton runat="server" CausesValidation="false" ID="QuickEnergyPrice" OnClientClick="Javascript:return false;" CssClass="button subcontent"><span>Get a quick energy price</span></asp:LinkButton>
</div>
<div class="not-for-sale">
<cms:ContentBlock ID="preservedTariffsLinkInfo" SkinID="Public/OurPrices/PreservedTariffsLinkInfo" runat="server" />
<p>
<asp:LinkButton runat="server" CausesValidation="false" ID="ViewNotAvailableTariffs" OnClick="RedirectToUnavailableTariffs" cssclass="arrow">View tariffs not available for sale</asp:LinkButton>
</p>
</div>
</asp:panel>
Code Behind:
protected void PostCodeChange_BtnClick(object sender, EventArgs e)
{
if (IsValid)
{
tcrpanel.ApplyPostcodeUpdate(postcode.EnteredPostCode);
tcrpanel.TcrUpdatePanel.Update();
}
else
{
TariffContainer.CssClass = "formContentHidden";
}
}
Update - The button click event is coming from a user control & this is wired up to trigger an update on an update panel - i.e. a partial postback is happening. I'm doing this hiding & showing of the div in the containing aspx page & even though all the server side page events are executing I'm guessing that the content of the page isn't getting re-rendered so I'm not seeing my changes.
The Solution - I ended up squirting a bit of javascript down from the server:
protected void PostCodeChange_BtnClick(object sender, EventArgs e)
{
tcrpanel.ApplyPostcodeUpdate(postcode.EnteredPostCode);
tcrpanel.TcrUpdatePanel.Update();
}
Then in the tcrpanel user control code behind:
public void ApplyPostcodeUpdate(string postcode)
{
if (IsValid)
{
BuildStartUpScript("showTariffContainer();");
}
else
{
BuildStartUpScript("hideTariffContainer();");
}
}
private void BuildStartUpScript(string functionCall)
{
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
script.AppendLine(functionCall);
script.AppendLine("</script>");
ScriptManager.RegisterStartupScript(pnlUpdateTcr, pnlUpdateTcr.GetType(), "HideTariffContainerScript", script.ToString(), false);
}
Then in the included JS file:
function hideTariffContainer() {
$("div.formContentVisible").toggleClass().toggleClass("formContentHidden");
}
function showTariffContainer() {
$("div.formContentHidden").toggleClass().toggleClass("formContentVisible");
}
As suspected, the problem was that a partial postback was occurring in which only the contents of the update panel were being re-rendered.
That said, all the server side page lifecycle events were still being invoked. This is what confused me as I could debug and see the CssClass being applied but not being rendered in the html. Just the way Asp.Net update panels work I guess.
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.
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
how to prevent refresh on asp.net c# web page button?
protected void Button1_Click(object sender, EventArgs e)
{
}
Regards
you must use this way :
<asp:button ID="btn" runat="server" Text="Button" onClientclick="btn_Click(event);"> </asp:button>
<script>
function btn_Click (e)
{
if(//Check somthing)
e.preventDefault();
}
</script>
Short answer, you can't.
However, using methods such as ajax, you can hide the appearance of the postback.
you can do it by creating a cookie inside your Button1_Click method. The first instruction within this method should check if that cookie exists or has not expired. In case itdoesn't exist or it expired, the follow line will create or update the cookie. In case the cookie exists,
return;
Sorry i cant give code cause im using my mobile.
I have an button in my Jquery mobile page, which is using asp.net webform.
<asp:Button ID="btnSeacrh" runat="server" Text="Search" OnClick="btnSeacrh_Click" />
Which is enabling asp:panel via this simple code on backend
protected void btnSeacrh_Click(object sender, EventArgs e)
{
pnlSearch.Visible = true;
}
Now, when I am clicking this button nothing happened but the URL is extended with the # keyword.
Ex. Previously it was
http://localhost:4989/MobileApp/CreateOrderByText.aspx
After clicking
http://localhost:4989/MobileApp/CreateOrderByText.aspx#/MobileApp/CreateOrderByText.aspx
But it is not showing the panel.
Any help ?
The code you posted looks fine, so I would assume the problem is elsewhere: are there any javascript errors on the page?