Executing Javascript code after submission of asp.net form - asp.net

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

Related

Can't Change CssClass From Code Behind

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.

Displaying and hiding parts of the web form freely without limitations in order to avoid ViewState loading problems

The problem
I have a web form and I would like to hide and show some panels. When I say "Panel" I do not mean the Panel control but just a pane in the html (usually represented by a DIV).
Well I want to show and hide this panels as I wish... no limits means that not necessarly only one pane must by visible, also 2, 3 or 4 can be.
Usually I achieved this by:
<div id="mypane1" runat="server">
...
</div>
<div id="mypane2" runat="server">
...
</div>
<div id="mypane3" runat="server">
...
</div>
and this:
this.mypane1.Visible = true;
this.mypane2.Visible = false;
this.mypane3.Visible = true;
Unfortunately these panels contain controls and some of them are not shown from the beginning (first web form load, so when no PostBack happens). This leads to problems for ViewState loading.
Regarding ViewState loading
Of course many will obviously ask about these ViewState problems of mine. Well, briefly, the thing is this: a ViewState loading error is not easy to manage but in the end I could understand the following.
Let's say to have this:
<!-- In .aspx -->
<div id="mypane1" runat="server">
...
<asp:Literal ID="..." runat="server" ...></asp:Literal>
<asp:TextBox ID="..." runat="server" ...></asp:TextBox>
...
</div>
<div id="mypane2" runat="server">
...
<asp:LinkButton ID="lb1" OnClick="lb1_Click" runat="server" ...></asp:LinkButton>
<asp:LinkButton ID="lb2" OnClick="lb2_Click" runat="server" ...></asp:LinkButton>
<asp:LinkButton ID="lb3" OnClick="lb3_Click" runat="server" ...></asp:LinkButton>
...
</div>
<div id="mypane3" runat="server">
...
<asp:TextBox ID="..." runat="server" ...></asp:TextBox>
<asp:LinkButton ID="lb4" OnClick="lb4_Click" runat="server" ...></asp:LinkButton>
<asp:TextBox ID="..." runat="server" ...></asp:TextBox>
...
</div>
// In .aspx.cs
protected void Page_Load(...) {
if (!this.IsPostBack) {
this.mypane1.Visible = true;
this.mypane2.Visible = false;
this.mypane3.Visible = true;
}
}
/// ... In the page many happens and the panes are shown and hidden ... ///
// Event Handlers
protected void lb1_Click(object sender, EventArgs e) {
...
}
protected void lb2_Click(object sender, EventArgs e) {
...
}
protected void lb3_Click(object sender, EventArgs e) {
...
}
protected void lb4_Click(object sender, EventArgs e) {
...
}
Well the problem is the following.
At the beginning pane2 is not shown.
After some actions pane2 is shown and its controls are shown too.
User click lb1 --> ViewState error
Note that the same happens for every event associated to pane2's controls. Is lb4 is pressed, no problems.
The problem is that the beginning hierarchy is represented by controls in pane 1 and 3. When events are raised by controls not part if the beginning hierarchy, ViewState is found inconsistent (because I act on HtmlControls, usually ServerControls are more intelligent and can manage better ViewState when controls are added inside them).
Feasible solutoions
Note that I could simply do the following to hide and show panels:
this.mypane2.Attributes.Add("display", "none");
This is not something I would like to do for two reasons:
I want panes not to be rendered as Html.
I would like to use server controls.
Request
I need to use web controls to manage my panel management, I cannot use HtmlControls because Control Hierarchy is not correctly loaded.
I tried MultiView and View controls but they enable me to use only one active view. How can I do?
Note: Please do not focus too much on the ViewState problem, it is just a good desc to let you know what happens, my only interest is to find a way to hide and show panes freely using server controls.
Thankyou
I'm assuming that setting the visiblity to false for the panels causes the children not to be added to ViewState or interfers with it in some way. Is that correct?
Given that, if you want to have the controls there as far as the .Net rendering engine is concerned but hidden from the end user you could try to show and hide them using css i.e.
show
pnlDemo.Attributes.Add("style", "display:block");
hide
pnlDemo.Attributes.Add("style", "display:none");
I had a situation where I needed ASP.Net controls there for ViewState purpose but not shown. At the appropriate point I would show them using JQuery and this method work for that scenario so it may work for yours.
Have you tried using the ViewStateModeByIdAttribute?
The ViewStateModeByIdAttribute class is used to specify a control that requires view-state loading by ID. The default view-state loading behavior is for ASP.NET to load the view-state information for a control by its index in the control tree of the page. There is a performance cost for loading view-state information by ID because the page control tree must be searched for the control specifically before loading its view-state information.
Have you tried with page.RegisterStartupScript .
script will load at the end of page load so control will have their viewstate .
Write JavaScript code that get the id of panel to hide & change the CSS to visibility hidden not display none.
another asp button on which you want to display the panel.
you can write JavaScript code onClientClick event of button to change the CSS of panel to change its visibility.

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.

InnerHTML attribute empty on span tag during page submit - jQuery/ASP.NET

I have a hidden TextBox control on my page that updates a span tag on the keyup event using jQuery. When the page is posted back to the server, the innerHTML attribute is empty.
How do I get the value that was set during the keyup event?
Client side code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#MyHiddenTextBox').keyup(function(){
if($(this).val().length > 0){
SetSpanValue();
}
});
});
function SetSpanValue() {
var mytext = $('#MyHiddenTextBox').val();
$('#MySpanTag').html(mytext);
}
</script>
<style type="text/css">
.USBBox
{
position: absolute;
left: -999em;
}
</style>
<asp:TextBox ID="MyHiddenTextBox" runat="server" CssClass="USBBox" />
<span id="MySpanTag" runat="server" enableviewstate="true" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
Server side code
protected void btnSubmit_Click(object sender, EventArgs e)
{
string x = MySpanTag.InnerHtml; //this is coming back empty
}
Remember that asp.net is still built on top of html form submissions, and with html forms only input and select tags are submitted back to the server. So you need to make your javascript update an input of some type (hidden would work just fine) at the same time it updates the span.
Span tags are not posted back to the server, they are not input controls, regardless of runat or enableviewstate settings. I would recommend entering the data into an input element when entered into the span tag, then you can access the value of that input element (TextBox/HiddenField etc) when the postback occurrs.
The contents of the element are not sent to the server in a postback.
All EnableViewState="true" does for you is tracks the changes made to the InnerHtml on the server.
You'll need to put the data into a hidden input.
In addition to the fact that you cannot capture span values on postback (as others have answered)... ASP.Net will not accept values set via javascript for hidden form fields because it considers this a security threat.
I have gotten around this in the past by making the form field visible but hosting it inside a hidden div. Then you can set the value of the textbox and it will be posted back to the server.
<div style="display:none;"><asp:TextBox id="MyHiddenTextBox" runat="server" /></div>

Resources