i have a form on a particular ASPX page that has custom js validation. Also on this form is a navigation menu in the header.
The navigation menu items are built programatically and are initiated by __doPostBack calls which obviously submits the form.
The problem i am having is that the form itself has code something like the following
onsubmit='return validateForm()'
and if the form has not been filled out then the form cant submit. This in itself is not a problem unless a user goes to the form but decides to navigate away.
When this happens the validateForm function fails.
Does anyone have a workaround for this issue?
NB: On my nav links i have already set CausesValidation="False"
This is the markup:
<div id="divNavigate" class="absolute_topleft">
<asp:LinkButton ID="linkGoHome" runat="server" OnClick="linkGoHome_Click" CausesValidation="false" CssClass="xxx">text.</asp:LinkButton>
</div>
This is the handler:
protected void linkGoHome_Click(object sender, EventArgs e)
{
Response.Redirect("xxxxx");
}
This is the validation function:
function validateTextField(field) {
var fieldElement = document.getElementById(field);
var validated = false;
if (fieldElement.value.length > 0) {
validated = true;
}
return validated;
}
And this is how its called:
<form id="formLogin" runat="server" onsubmit="return validateTextField(field1)">
Are your navigation links proper asp.net server controls? If they are setting CausesValidation="False" should prevent them from causing validation. Can you post the code where you are dynamically adding them to the page, the most liekly explanation is the the CausesValidation property is not being set corectly.
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.
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 asp.net linkButton (or imageButton) control in my profile.aspx page. I'am checking Request.Querystring("id") in the page below in the code behind.
http: //localhost:42932/profile.aspx?id=1
When I first load the profile page it is not posted back. It is ok!. When I go to another users profile (the same page just the query string is different) using imageButton control with the adddress;
http: //localhost:42932/profile.aspx?id=2
it is posted back. I dont want it to be posted back. But if I go to this page with a regular html input element like
a href = "http: //localhost:42932/profile.aspx?id=2"
it is not posted back. So I want the image button behave like an html input element.
Here is my imageButton;
ASPX:
<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server"/>
.CS
imgProfile.PostBackUrl = "profile.aspx?id=" + Session["userID"];
Edit:
if (!IsPostBack)
{
Session["order"] = 0;
}
This control is in the page load. So it should be !postback with state I mentioned above. Because all the other functions are working when Session["order"] = 0
Make use of OnCLientClick instead of OnClick, so that you only run client side code. Then, sepcify that you return false;
i.e.
<asp:ImageButton ID="imgProfile" ImageUrl="images/site/profile1.png" runat="server" OnClientClick="return false;" />
But, why use a server control, when this can be done with a normal <img .. html control?
Rather than specifying a PostBackUrl I would recommend using Response.Redirect() in the button click event handler:
public void imgProfile_Click(object sender, eventArgs e){
Response.Redirect("profile.aspx?id=" + Session["userID"]);
}
Or alternatively, just use a Hyperlink control and set the NavigateUrl property during Page_Load:
<asp:HyperLink ID="imgProfile" runat="server"><img src="images/site/profile1.png" /></asp:Hyperlink>
imgProfile.NavigateUrl = "profile.aspx?id=" + Session["userID"];
How do I execute Javascript after submission of an ASP.NET form?
For example, if I got a submit button click after submission of page then I want to display a DIV which I have hidden on page.
Since you are using a full postback, you can easily include the javascript from the code-behind.
Place your JavaScript Code inside a Placeholder
<asp:Placeholder ID="javascriptPlaceholder" runat="server" Visible="false">
<%-- Your Javascript here -->
</asp:Placeholder>
I assume in your OnClick handling method, you are getting the value of the form and do something else with it. In this method you could set the Visibile property of the placeholder:
this.javascriptPlaceholder.Visible = true;
If you would only want to convert the hidden div to a visible one then that can be done on the server side. In the aspx, give the div an id and a runat="server". Then in the server side, set its display style attribute to 'block'. For example, say the div is defined as
<div id="divTest" runat="server" style="display:none;">
This is a div test
</div>
Then in the post event of the submit button you can set its style as given below:
divTest.Style["display"] = "block";
If you only want to emit scripts after the post then using the ScriptManager you could use:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptRegisterTest", "alert('Testing');", true);
Maybe I'm not understanding your question, but if you're going back to the server and doing some processing, why do you need javascript? Just add a runat="server" to the div in question and make it visible after the processing.
<div id="YourDiv" runat="server" Visible="false" >
...Whatever is here
</div>
Code Behind:
protected void Button_Click(object sender, EventArgs e)
{
/*
Your Logic Here
*/
YourDiv.Visible = true;
}
I have a link on the page and i want when the user is pressing it, to evaluate a method where i check if the usser is logged in. If not, i want to show up a modal popup.
I know how to do the back-end checking and how to redirect the user but i have problems
with the link button:
<asp:LinkButton ID="LinkButton1" runat="server"
OnClientClick="redirectToWishList()">LinkButton</asp:LinkButton>
When i press it, it does a full postback instead evaluating the method where i show up the modal pop.
Do you have any workaround to not fire a full postback but check the method where i am doing the redirect?
Ps: The method which has to fire:
public void redirectToWishList(object sender, EventArgs e)
{
ASP.usercontrols_loginpopup_ascx loginUserControl = (ASP.usercontrols_loginpopup_ascx)UtilsStatic.FindControlRecursive(Page, "loginPopUp");
ModalPopupExtender modal = (ModalPopupExtender)loginUserControl.FindControl("loginPopUp");
modal.Show();
}
You need to call redirectToWishList as a function (including the parens): redirectToWishList()
<asp:LinkButton ID="LinkButton1" runat="server"
OnClientClick="redirectToWishList();return false;">LinkButton</asp:LinkButton>
Also, if you return false in your function, you do not need to in the tag.
UPDATE
I misunderstood. The OnClientClick is for invoking JavaScript, not running methods in your code-behind. You need to OnClick instead.
Do you return false from your redirectToWishList function?
You shouldn't need the return false in the LinkButton declaration.