How to maintain div contents after post back? - c#

I have a panel on a page which it's contents are changed client side. For example, I have the following web form:
<asp:panel id="panContents" runat="server">
<span>Initial content</span>
</asp:panel>
The following jQuery snippet replaces the contents of the div client side when the page is first loaded:
$("<%= panContents.ClientId =>")
.html("<span>Some content to be maintained after postback</span>")
After the page is submitted and returned to the client, the contents of the panel reverts back to as when the page was first loaded:
<div>
<span>Initial content</span>
</div>
Is it possible to maintain the contents of the panel after post back so that it appears the same before being submitted? So I end up with the following after post back:
<div>
<span>Some content to be maintained after postback</span>
</div>

The content of panel vanishes because you are just manipulating the DOM. If you want to retain the value of panel first put it into a hidden field and after post back reassign the text to panel

This content exists only on a client, since Panel does not post any content to the server (somewhat obviously). The workaround you might want to apply to check if you need to run the snippet on the page load. For this you might want a hidden field with a flag.
Here is a dirty proof of concept:
<asp:HiddenField ID="ReplacePanelFlag" runat="server" Value="0" />
// check flag on page load
$(function() {
if ($("<%= ReplacePanelFlag.ClientID %>").val() === "1") {
//run snippet
}
});
// in snippet make sure to set the flag to "1"
$("<%= panContents.ClientId =>")
.html("<span>Some content to be maintained after postback</span>");
$("<%= ReplacePanelFlag.ClientID %>").val("1");

Related

Panel inside button not working properly in asp.net

In my application i have 3 panels corresponding anchor tags. Initially when the page is load first panel is visible rest of two panels is in disable state. when i click second anchor tag it is not displaying once it display in that when i click button data is not display properly i need to display when i click anchor tag corresponding panel data will be display
Remove following part from your code.
$("#<%= btnGetAct.ClientID %>").click(function () {
$("#<%= pnlPw.ClientID %>").hide();
$("#<%= pnlAct.ClientID %>").show();
$("#<%= pnlUserdetails.ClientID %>").hide();
});
You are calling this Click from both side. From your client side as well as server side so I think it is creating conflict and because of that you're not getting your desired output.
You can remove the show/hide init of your panels in your $(document).ready function to prevent resetting to the initial state every time your page is loaded, for example when you're clicking your GET button.
You can set this initial state directly in your aspx code, setting a display:none to the panels you want to hide at start:
<asp:Panel ID="pnlAct" runat="server" Style="display:none;"> [...] </asp:Panel>
<asp:Panel ID="pnlUserdetails" runat="server" Style="display:none;"> [...] </asp:Panel>
Comment/remove theses lines in your JavaScript:
//$("#<%= pnlPw.ClientID %>").show();
//$("#<%= pnlAct.ClientID %>").hide();
//$("#<%= pnlUserdetails.ClientID %>").hide();
Then, your code should work properly.

Invalid ViewState when using jQuery tabs

I have a fairly simple page with a set of jQuery tabs, the content of some is called via ajax. I also have a search box in the masterpage in my header.
When I open the tabbed page the search box works fine. However once I have clicked on one of the ajax tabs the search box fails to work with an "Invalid Viewstate" yellow screen of death.
I believe this is because the ajax page is replacing the __VIEWSTATE hidden input with its own.
How can I stop this behaviour?
UPDATE: I have noticed that the YSOD only appears in IE and Chrome, Firefox doesn't seem to have the same issue. Although how the browser influences the ViewState, I'm not sure.
UPDATE: I've put a cut down version of the site that shows the issue here: http://dropbox.com/s/7wqgjqqdorgp958/stackoverflow.zip
The reason of such behavior is that you getting content of the ajaxTab.aspx page asynchronously and paste it into another aspx page. So you getting two instances of hidden fields with __VIEWSTATE name and when page posted back to server theirs values are mixing (might depends on how browser process multiple controls with same name on submit). To resolve this you can put second tab's content into a frame:
<div id="tabs">
<ul>
<li>Default Tab</li>
<li>ajax Content</li>
</ul>
<div id="tabs-1">
<p>
To replicate the error:
<ul>
<li>First use the search box top right to search to prove that code is ok</li>
<li>Then click the second ajax tab, and search again.</li>
<li>N.B. Chrome / IE give a state error, Firefox does not</li>
</ul>
</p>
</div>
<iframe id="tabs-2" src="ajaxTab.aspx" style="width:100%;" ></iframe>
</div>
Also, I'm not sure but this seems like error in the Web_UserControls_search control. In my opinion, NavBarSearchItemNoSearchItem_OnClick method must be refactored as below:
protected void NavBarSearchItemNoSearchItem_OnClick(object sender, EventArgs e)
{
var searchFieldTbx = NavBarSearchItemNo;
var navBarSearchCatHiddenField = NavBarSearchCatHiddenField;
var term = searchFieldTbx != null ? searchFieldTbx.Text : "";
if (term.Length > 0) //There is actually something in the input box we can work with
{
//Response.Redirect(Url.GetUrl("SearchResults", term));
Response.Redirect(ResolveClientUrl("~/Web/SearchResults.aspx?term=" + term + "&cat=" + navBarSearchCatHiddenField.Value));
}
}
Draw attention that we resolving client url when redirecting to search results page and instead of navBarSearchCatHiddenField use navBarSearchCatHiddenField.Value as cat parameter.
I guess that you use AJAX to fill the content of the tab. So in this case, content of your tab will be replaced by the new one from ajax and certainly _VIEWSTATE will be replaced. At server, do you use data from ViewState? In the "static tabs", you should prevent them auto reload by using cache:true
Your issue is that with your ajax call you bring in a complete ASPX page. Including the Form tag and its Viewstate. If you remove the Form tag from ajaxTab.aspx you will see everything works fine. asp.net does not know how to handle two Form tags in one page. Same goes for hidden Viewstate fields. You cannot bring in a full aspx page via ajax. Just bring in the content Div you want to display and you`ll be good to go.

How to Update the Div Content without generating all the content of a html File

I have an HTML file inside <body /> tag with structure:
<div id='header'>content of header</div>
<div id='content'>content of content.</div>
<div id='footer'>content of footer</div>
The content of header, content and footer are changed as per user interaction.
User selects content for header section, The header section adds the user content to the header <div />.
For this I made three stringbuilder variables respective to the three <div />s in c#, whenever there is a change in any <div /> the respective string builder variable updates and I am making an HTML temp file with <head /> section and a <body /> section—and finally appending all the string builders to the <body /> tag and saving the file. And if user wants to download the file, the file should have all the updates.
How to update the particular <div /> content from code behind with c# with out making temp file?
I need changes directly on the file and I don't want to redesign the temp page in code behind.
using update panel can resolve your issue.
just update the div in your codebehind.
http://ajax.net-tutorials.com/controls/updatepanel-control/
You can use the following code for changing the content of specific Div.
Try the following code in your code behind file
For Header
header.InnerText = "Changed content of header";
same for other divs.
You could indeed use updatepanel like mentioned above or even better, make an asynchrone call in javascript to your server and update the element of choice with the response.
You could use jQuery (see: jQuery.com) for the async call (e.g. with $.getJSON or $.ajax) and modify the contents of the div with jQuery to like: $("#header").html(yourResult).
The call to the server could be handled by a handler (.ashx) or WCF service or whatever works for you.
Hope this gets you further!
Cheers!

C# Script output in aspx page

I am having issues with the output of my C# script embedded in my asp.net code. The output is generated after clicking a submit button for a web form. This web form is at the top of the page. The output, when clicking submit, is currently being placed above the web form which is in turn pushing the web form underneath it. I would like the opposite to happen. I want it to output below my web form. The way I generate output from my script is as follows:
Response.Write("<p>");
foreach(obj in arr){
Response.Write(obj);
}
Response.Write("</p>");
Also if it matters, I initialize the script with runat="server". The script gets called when the user selects "submit" near the web form. Thanks in advance. I've been trying to format this thing for quite some time now.
You would be better off putting a 'literal' object in the place on your page precisely where where you want the result to appear, and then, instead of spitting out HTML with response.write, you assign the desired text to the literal in your code-behind.
Like this:
<html>
<p>
<asp:Literal ID="ltlTest" runat="server"></asp:Literal>
</p>
</html>
and then in your code behind:
ltlTest.Text = "the string you want to show...";
You can include html tags in the string assignment, though generally I try not to.
You've got some choices.
You can make arr a public property, and then use <% foreach (var obj in arr) Response.Write(obj); %> directly in the page markup where you want it.
You can put in an <asp:Literal runat="server" ID="Literal1"> control and then set Literal1.Text = ... in your code. This achieves the same, but with ViewState (so the value is persisted on postbacks).
If you'd like the result to be rendered within <span /> tags, you can use an <asp:Label /> control. This is usually the best choice for displaying messages to the user.

How do I generate JavaScript during an AJAX callback (postback) and then execute it on the browser?

In summary:
I have an ASP.NET web page that causes an AJAX postback to the server. When this event handler runs (in the code behind) it will generate some JavaScript that I then want to run in the client. Not sure how to achieve this.
In Detail:
I have an ASP.NET web page with multiple items displayed on the page.
As a "nice to have", I want to display either a green circle or a red cross next to each item (these differ depending upon each item). Since it isn't vital for the User to see these icons and also because it takes several seconds to work out which icon should be shown for each item, I want to perform this after the page has loaded, so in an AJAX callback.
My thought therefore was this. When creating the page, I would create both icons next to each object and create them with the style of "hidden". I would also make a note of each one's client ID.
Then, when the callback occurs, I fetch the necessary data from the database and then create a JavaScript function that changes the display for each of the icons I want to show from "hidden" to "visible".
I thought I could achieve this using the ScriptManager object.
Here's a very trivial version of my server side code (C#)
void AjaxHandler(object sender, EventArgs e)
{
// call to database
string jscript = "alert('wibble');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript);
}
Obviously, here I'm just trying to get an alert to fire after the postback has occurred...in real life I'd have my JavaScript function to change the display of all the icons I want to display.
When I run this, the serverside code runs and yet nothing happens in the server.
I have also tried:
ScriptManager.RegisterClientScriptBlock()
Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()
Page.ClientScript.RegisterStartupScript()
Page.ClientScript.RegisterClientScriptBlock()
but none of them work....
FireFox shows the following JavaScript error:
Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://localhost/MyWebSiteName/Telerik.Web.UI.WebResource.axd?_TSM_HiddenField_=ctl00_RadScriptManager1_TSM&compress=1&_TSM_CombinedScripts_=%3b%3bSystem.Web.Extensions%2c+Version%3d3.5.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3d31bf3856ad364e35%3aen-US%3a3de828f0-5e0d-4c7d-a36b-56a9773c0def%3aea597d4b%3ab25378d2%3bTelerik.Web.UI%2c+Version%3d2009.3.1314.20%2c+Culture%3dneutral%2c+PublicKeyToken%3d121fae78165ba3d4%3aen-US%3aec1048f9-7413-49ac-913a-b3b534cde186%3a16e4e7cd%3aed16cbdc%3a874f8ea2%3af7645509%3a24ee1bba%3a19620875%3a39040b5c%3af85f9819 Line: 1075"]
Does anyone know if what I am trying to do is even allowed?
If not - what's my alternative?
Thank you
Since your script doesn't have enclosing <script> tags, you need to use this form of RegisterStartupScript:
ScriptManager.RegisterStartupScript(this, this.GetType(), "uniqueKey", jscript, true);
You said your initial goal was:
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Here's a way you can do that:
given:
<asp:ScriptManager runat="server" ID="scriptManager">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args) {
var dataItems = args.get_dataItems();
for(var key in dataItems){
if(/^javascript:/.test(dataItems[key])){
eval(dataItems[key].substring("javascript:".length));
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
</script>
<asp:UpdatePanel runat="server" ID="pnl">
<ContentTemplate>
<asp:Button runat="server" ID="btnClick" Text="Click me!" OnClick="btnClick_Click" />
</ContentTemplate>
</asp:UpdatePanel>
You can create a click handler that does this:
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterDataItem(this, "javascript:alert('hello world!');");
}
What's happening is during the postback, the page request manager is sent a data item your code-behind. That data-item happens to be a javascript command. After the postback, the client side script manager's endRequest handler is checking for data items. Normally you'd want to see who those items are for, which is apparent by the key of the item (it's the client ID of the control that is the target of the data being sent). In your case, you could load this up with the javascript that you want to fire, tell yourself that it's a javascript because it's prepended, then dynamically evaluate the script.
So in this example, clicking the "Click Me!" button will generate a Hello World prompt whose script was actually created by the code-behind during the postback.
You'll have to be very cautious with this approach until you're comfy - I'd avoid references to "this"...
Happy coding.
B
Okay
The idea was that the page would load, data would be sent (AJAX) to the server. The server would then generate some JavaScript based upon this data and send that back to the page. That JavaScript would then run updating the page in a specific way.
Couldn't get that to work....
I got around this in the following way:
When the page loads, data is sent (AJAX) to the server. This processes the data and serialises the results updating a hidden text element, which goes back to the browser. Meanwhile, I have a JavaScript timer on the page that runs a JavaScript function that was generated when the page first loads. This function looks at the hidden text element. If that element has text (the result of the postback) then it shuts down the timer, deserialises the data and then works out how to update the page.

Categories

Resources