Can't Change CssClass From Code Behind - asp.net

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.

Related

asp:Button - onclick event fires code on a different code-behind?

I'm teaching myself to use a site.master page with child webforms embedded using the ContentPlaceHolderID object. I'm figuring it out, but I have one question; is it possible to put a button on the site.master page that fires code on the codebehind pages of the child forms? If I can do that, it will really simplify what I'm trying to accomplish.
I tried to 'inherit' both codebehinds, but of course that didn't work. Is there a way to do this?
Yes there is a way to do this. You need to set UseSubmitBehavior button property to false and then you can access the control that causes the post back using Request.Params.Get("__EVENTTARGET"); So the code would look like this:
Button definition in Site.Master markup:
<asp:Button ID="MyButton" runat="server" Text="Button" UseSubmitBehavior="false" />
code behind within any inherited page:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// in case you have code to be executed on first load
}
else
{
string myButtonCtrl = Request.Params.Get("__EVENTTARGET");
if (myButtonCtrl != null && myButtonCtrl.EndsWith("MyButton"))
{
// MyButton has been clicked!
}
}
}

How can I stop refreshing the page in the else condition

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

Executing Javascript code after submission of asp.net form

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;
}

2 onclick events on 1 Div ? (ASP.NET / HTML)

I'm using Div's, now I have to handle 2 Events with one Div-Click..
On the Button I would take, once onclick="" and OnClientClick.. but if I use a Div I can't use OnClientClick :(
Can you guys tell me, what I shall do, to get this? (there is one JavaScript method and one codebehind method, which I want to call) - till now I can call only one.
after wizards help:
got this:
<asp:Button ID="fakeButton" runat="server" Text="dummy" onclick="dummyButton_Click" style="display:none" />
and JS:
alert("div clicked");
document.getElementById("<%=fakeButton.ClientID%>").click();
So but he dont enters the Method:
protected void dummyButton_Click(object sender, EventArgs e) { } ..
i putted a breakpoint, he never entered, only showed the alert.. –
First, add dummy hidden button with the proper server side click event:
<asp:Button id="fakeButton" runat="server" OnClick="MyMethod" Text="dummy" style="display: none;" />
Second, have such code for the DIV:
<div onclick="DivClick();">text here...</div>
And finally such client side code:
function DivClick() {
//your client side code here...
//e.g.
alert("div clicked");
//now invoke server side click as well:
document.getElementById("<%=fakeButton.ClientID%>").click();
}
This will first execute your client side code e.g. the alert, then "auto click" the button and by this causing post back and the server side code to execute.
If you don't want full reload, try putting it all inside UpdatePanel.

How to bypass onSubmit Form validation in ASPX page

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.

Resources