UpdatePanel and Javascript - c#

I have inline script such as this, which toggles between an edit and a display divs. If it is inside the the UpdatePanel it requires two click before it works. If I remove the UpdatePanel it works fine with a single click.
Edit
Can anyone help please?
Thanks
EDIT:
Edit function:
function edit(e, id) {
var editdiv = $('#' + id).find('.edit');
var cntdiv = $('#' + id).find('.content');
if (editdiv.css('visibility') == 'hidden') {
editdiv.css('visibility') == 'visible'
cntdiv.css('visibility') == 'hidden'
cntdiv.hide();
editbox.show()
}
else {
editdiv.css('visibility') == 'hidden'
cntdiv.css('visibility') == 'visible'
cntbox.show();
editbox.hide()
}
stopEventBubble(e); // Code to cancel event bubbling;
}

Are you using the ScriptManager to register the edit function?
protected void Page_Load(object sender, EventArgs e)
{
string jsEdit = #"function edit(event, id) {}";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "editFunction", jsEdit);
}
If your code is in an external file, you can register it with the ScriptManager or the ScriptManagerProxy in the aspx for your page:
<ScriptManager runat="server" id="ScriptManager1">
<Scripts>
<asp:ScriptReference path="~/js/edit.js" />
</Scripts>
</asp:ScriptManager>
EDIT:
alright, I know what the issue is now. You aren't setting the css visibility to begin with. So either you need to set the css visibility or you can modify your edit function to follow the following logic:
function edit(e, id) {
var editdiv = $('#' + id).find('.edit');
var cntdiv = $('#' + id).find('.content');
//I reversed it to look for visible instead of hidden. The main problem with this approach and your other approach is that the original value is inherited.
if (editdiv.css('visibility') == 'visible') {
editdiv.css('visibility') == 'hidden'
cntdiv.css('visibility') == 'visible'
cntbox.show();
editbox.hide()
}
else {
editdiv.css('visibility') == 'visible'
cntdiv.css('visibility') == 'hidden'
cntdiv.hide();
editbox.show()
}
stopEventBubble(e); // Code to cancel event bubbling;
}
The other option will require you to set the following in you "edit" and "content" divs.
<div id="edit" style="visibility:hidden"> ... </div>
<div id="content" style="visibility:visible"> ... </div>
If you need further help, I'll need to see your aspx code concerning the UpdatePanel, edit, and content.

Try this:
Edit
Edit
As Chris said:
If you are injecting the function when you click the Edit link the function won't exist the first time you click an Edit link.
What you could do is add the function inside a <script> tag in the <head> section of the markup:
<head>
<script>
function edit(event, id) {
// Your code here
}
</script>
</head>
Or in a separate .js file.

Related

How to set Textbox's Text as an querystring argument for LinkButton without having codebhind file?

I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>

Programmatically adding a hyperlink to a bulleted list that IS NOT DisplayMode=Hyperlink

I have a ASP.NET bulleted list control that, until today, was created and used only for plain text. A new design request asks that I turn SOME of those items into hyperlinks. Therefore the bulleted list will ultimately need to contain some plain text items, and some hyperlinks. If I change it to DisplayMode=Hyperlink, even if I leave the value blank, the entries that should just be plain text still become clickable links.
One solution that I think I can make work, is to use a Literal control and use HTML (<a href...) on the lines that need to be links. That will entail a little bit of re-working some old code, so before I try that I really want to know if this is possible to do with the existing BulletedList.
EDIT:
I seriously couldn't find anything about this anywhere, and I generally consider myself a pretty good Googler. So for the one or two lost and confused souls who find themselves in the same scenario sometime in the next decade, here is my complete implementation of the excellent answer offered below:
In the page's code-behind:
foreach (SupportLog x in ordered)
{
blschedule.Items.Add(new ListItem(x.Headline, "http://mysite/Support/editsupportlog.aspx?SupportLogID=" + x.SupportLogID));
}
blschedule.DataBind();
Note the DataBind at the end --- this is necessary to fall into the DataBound event:
protected void blschedule_DataBound(object sender, EventArgs e)
{
foreach (ListItem x in blschedule.Items)
{
if (x.Value.Contains("http")) //an item that should be a link is gonna have http in it, so check for that
{
x.Attributes.Add("data-url", x.Value);
}
}
}
In the .aspx page's head:
<script src="<%# ResolveClientUrl("~/jquery/jquery141.js") %>" type="text/javascript"></script>
<script>
$(document).ready(function () {
$('#<%=blschedule.ClientID %> li').each(function () {
var $this = $(this);
var attr = $this.attr('data-url');
if (typeof attr !== 'undefined' && attr !== false) {
$this.html('' + $this.text() + '');
}
});
});
</script>
The if statement is required to make sure to only turn the items that have the "data-url" attribute into links, and not turn ALL items into links.
You may find it's easier to use an <asp:Repeater /> for that task.
Something like:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate>
<li><%# string.IsNullOrEmpty(Eval("url").ToString()) ? Eval("text") : string.Format("{1}", Eval("url").ToString(), Eval("text").ToString()) %></li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
Hackalicious Way
set the URL value to DataValueField when data binding the BulletedList
use the DataBound event to iterate through the items and add an attribute to each one with a URL value
protected void BulletedList1_DataBound(object sender, EventArgs e)
{
foreach (ListItem i in BulletedList1.Items)
{
if (i.Value.Length > 0)
{
i.Attributes.Add("data-url", i.Value);
}
}
}
use JavaScript/jQuery to apply the necessary markup:
$('[data-url]').each(function() {
var $this = $(this);
$this.html('' + $this.text() + '');
});
didn't test this jQuery but it should be close

Get variable & keep changes after postback

This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}

Javascript functions inside ASP.NET User Control

I created ASP.NET user control with javascript function :
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="BingTranslator.Web.WebUserControl1" %>
<script type="text/javascript">
function example() {
alert('<%=ExampleButton.ClientID%>');
return false;
}
</script>
<asp:Button ID="ExampleButton" runat="server" Text="Example"/>
I want to call "example" function when user move mouse to button, so I added attribute for button:
ExampleButton.Attributes.Add("onmouseover", "example()");
It works well, but when I need two controls on same page I got a problems. ASP.NET generates code with two functions with same name, what is wrong:
<script type="text/javascript">
function example() {
alert('TestControl1_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl1$ExampleButton" value="Example" id="TestControl1_ExampleButton" onmouseover="example()" />
<script type="text/javascript">
function example() {
alert('TestControl2_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl2$ExampleButton" value="Example" id="TestControl2_ExampleButton" onmouseover="example()" />
And always onmouseover event on any button will call second function. I am able resolve this issue by adding java script code with client Id directly to attriburte onmouseover.
ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]");
But it is not very harmonious solution as for me. Please advise, how I can better resolve such issue.
P.S. There will be much more Javascript code, I added two string upper just for example.
I found a solution in another site which allows you to use external file
if (!Page.ClientScript.IsClientScriptIncludeRegistered("key"))
{
string url = ResolveClientUrl("~/Scripts/file.js");
Page.ClientScript.RegisterClientScriptInclude("key", url);
}
You need to register your scripts with ClientScriptManager - this way they can be registered once, regardless of how often the control has been added to the page:
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
You need to use this.id
$(document).ready(function () {
load_v<%= this.ID %>
});
function load_v<%= this.ID %>(fromclick) {
alert('anything');
}
So that even if you need two or more same controls in the same page they will have different ids.
Hope this Helps! cheers :)

How to make TinyMCE work inside an UpdatePanel?

I'm trying to do something that many people seem to have been able to do but which I am unable to implement any solution. The TinyMCE control works pretty well in an asp.net form until you enclose it with an UpdatePanel, which then breaks after postback. I have tried some fixes like the RegisterClientScriptBlock method, but am still unsuccessful, I still lose the tinyMCE control after postback.
Below is a full test project (VS 2008) provided with a Control outside UpdatePanel and one inside, with a button on each to generate postback. Also in the project I have a EditorTest control which include commented code of some calls I tried, in case it gives anyone any ideas.
CODE SAMPLE
Here are some sources for some solutions on the MCE forum :
AJAX
UpdatePanel
To execute the init everytime the UpdatePanel changes you need to register the script using ScriptManager:
// control is your UpdatePanel
ScriptManager.RegisterStartupScript(control, control.GetType(), control.UniqueID, "your_tinymce_initfunc();", true);
NOTE: You cannot use exact mode on your init function, you can use either textareas or a class selector, or else it won't work properly.
You also have to use
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "", "tinyMCE.triggerSave();");
On a postback of a UpdatePanel the editor content isn't saved on the Textbox, because the default behavior is only for form.submit, so when you submit anything it will save the text before it posts.
On the code behind to get the value you will just need to access TextBox.Text property.
NOTE: If you are using the .NET GZipped you probably will have to drop it, I couldn't get it working, I had to remove this completely.
Ok, your problem is two fold. Stefy supplied you with part of the answer, which is you have to initialize TinyMCE on the postback by registering startup script like so:
using System.Web.UI;
namespace TinyMCEProblemDemo
{
public partial class EditorClean : UserControl
{
protected void Page_Load(object sender, System.EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page,
this.Page.GetType(), mce.ClientID, "callInt" + mce.ClientID + "();", true);
}
}
}
The second problem you have is with your implementation of a custom control. Designing custom controls is out of scope of this answer. Google can help you there.
You have multiple instances of your control on the page which can cause you issues with script, as it get rendered multiple times. This is how I modified your markup to solve your issue(notice dynamic naming of your script functions, custom controls should be self contained and mode: "exact" on the tinyMCE.init):
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="EditorClean.ascx.cs"
Inherits="TinyMCEProblemDemo.EditorClean" %>
<script type="text/javascript" src="Editor/tiny_mce.js"></script>
<script type="text/javascript">
function myCustomCleanup<%= mce.ClientID%>(type, value) {
if (type == "insert_to_editor") {
value = value.replace(/</gi, "<");
value = value.replace(/>/gi, ">");
}
return value;
}
function myCustomSaveContent<%= mce.ClientID%>(element_id, html, body) {
html = html.replace(/</gi, "<");
html = html.replace(/>/gi, ">");
return html;
}
function callInt<%= mce.ClientID%>() {
tinyMCE.init({
mode: "exact",
elements: "<%= mce.ClientID%>",
theme: "advanced",
skin: "o2k7",
plugins: "inlinepopups,paste,safari",
theme_advanced_buttons1: "fontselect,fontsizeselect,|,forecolor,backcolor,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,cut,copy,paste,pastetext,pasteword",
theme_advanced_buttons2: "",
theme_advanced_buttons3: "",
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
cleanup_callback: "myCustomCleanup<%= mce.ClientID%>",
save_callback: "myCustomSaveContent<%= mce.ClientID%>"
});
}
</script>
<textarea runat="server" id="mce" name="editor" cols="50" rows="15">Enter your text here...</textarea>
This solution no longer works for TinyMCE 4.2.3. Instead of using tinymce.mceRemoveControl() you now need to use tinymce.remove(). Here is a full working example:
The Page
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/Frame.master" AutoEventWireup="true" CodeFile="FullImplementation.aspx.cs"
Inherits="TinyMCE" ValidateRequest="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphContent" Runat="Server">
<asp:ScriptManager runat="server"/>
<asp:UpdatePanel runat="server" id="upUpdatPanel">
<ContentTemplate>
<asp:TextBox runat="server" id="tbHtmlEditor" TextMode="MultiLine">
Default editor text
</asp:TextBox>
<asp:Dropdownlist runat="server" ID="ddlTest" AutoPostBack="true" OnSelectedIndexChanged="ddlTest_SelectedIndexChanged">
<Items>
<asp:ListItem Text="A"></asp:ListItem>
<asp:ListItem Text="B"></asp:ListItem>
</Items>
</asp:Dropdownlist>
<asp:Button runat="server" ID="butSaveEditorContent" OnClick="butSaveEditorContent_Click" Text="Save Html Content"/>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
$(document).ready(function () {
/* initial load of editor */
LoadTinyMCE();
});
/* wire-up an event to re-add the editor */
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler_Page);
/* fire this event to remove the existing editor and re-initialize it*/
function EndRequestHandler_Page(sender, args) {
//1. Remove the existing TinyMCE instance of TinyMCE
tinymce.remove( "#<%=tbHtmlEditor.ClientID%>");
//2. Re-init the TinyMCE editor
LoadTinyMCE();
}
function BeforePostback() {
tinymce.triggerSave();
}
function LoadTinyMCE() {
/* initialize the TinyMCE editor */
tinymce.init({
selector: "#<%=tbHtmlEditor.ClientID%>",
plugins: "link, autolink",
default_link_target: "_blank",
toolbar: "undo redo | bold italic | link unlink | cut copy paste | bullist numlist",
menubar: false,
statusbar: false
});
}
</script>
</asp:Content>
The Code-Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TinyMCE : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// we have to tell the editor to re-save the date on Submit
if (!ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "SaveTextBoxBeforePostBack", "SaveTextBoxBeforePostBack()");
}
}
protected void butSaveEditorContent_Click(object sender, EventArgs e)
{
string htmlEncoded = WebUtility.HtmlEncode(tbHtmlEditor.Text);
}
private void SaveToDb(string htmlEncoded)
{
/// save to database column
}
protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
The correct way to make tinyMCE work in an updatepanel:
1) Create a handler for the OnClientClick of your "submit" button.
2) Run tinyMCE.execCommand("mceRemoveControl", false, '<%= txtMCE.ClientID %>'); in the handler, so as to remove the tinyMCE instance before the postback.
3) In your async postback, use the ScriptManager.RegisterStartupScript to run tinyMCE.execCommand("mceAddControl", true, '<%= txtMCE.ClientID %>');
Basically, all you need to do is use the mceRemoveControl command before the async postback and register a startup script to run the mceAddControl command after the async postback. Not too tough.
I did the following:
First I added the this Javascript to my page:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
function endRequestHandler(sender,args)
{
tinyMCE.idCounter=0;
tinyMCE.execCommand('mceAddControl',false,'htmlContent');
}
function UpdateTextArea()
{
tinyMCE.triggerSave(false,true);
}
</script>
Because I'm creating an ASP.NET and using and ASP.NET Button in my page, I had to add the following to the Page Load:
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick", "UpdateTextArea()");
}
This is an old question, but after hours searching and messing around looking for the answer, I feel obligated to post the solution I came up with.
It appears that, at least in the implementation I'm using (multiple editors inside an UpdatePanel) that tinyMCE must be informed the control is going away when the UpdatePanel submits, or else it will refuse to load it again.
So, in addition to the code to Init TinyMCE (which only needs to run when the whole page loads) you need to do this for each of your MCE textboxes:
ScriptManager.RegisterStartupScript(this, this.GetType(), elm1.UniqueID+"Add",
"tinyMCE.execCommand('mceAddControl', true,'" + elm1.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), elm1.UniqueID + "Remove",
"tinyMCE.execCommand('mceRemoveControl', true,'" + elm1.ClientID + "');");
elm1 is whatever the tinyMCE element is. Mine is a textarea residing in a UserControl, but you can apply it to any item you want to bind/unbind your textarea.
Updating the answer to this question for those using .NET framework 4, I was successful in attaching TinyMCE to a TextBox inside an update panel by inserting the following:
In markup within the <head></head> region:
<script src="scripts/tinymce/tinymce.min.js" type="text/javascript"></script>
<script type="text/javascript">
tinyMCE.init({
selector: ".tinymcetextarea",
mode: "textareas",
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
"searchreplace visualblocks visualchars code fullscreen autoresize insertdatetime media nonbreaking",
"save table contextmenu directionality emoticons template paste textcolor",
"autosave codesample colorpicker image imagetools importcss layer"
],
toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media | forecolor backcolor emoticons",
style_formats: [
{ title: 'Bold text', inline: 'b' },
{ title: 'Red text', inline: 'span', styles: { color: '#ff0000' } },
{ title: 'Red header', block: 'h1', styles: { color: '#ff0000' } },
{ title: 'Example 1', inline: 'span', classes: 'example1' },
{ title: 'Example 2', inline: 'span', classes: 'example2' },
{ title: 'Table styles' },
{ title: 'Table row 1', selector: 'tr', classes: 'tablerow1' }
]
});
</script>
In the markup within the <body></body> region:
<asp:TextBox ID="tbContentHtml" CssClass="tinymcetextarea" Wrap="true" runat="server" Width="90%" TextMode="MultiLine" />
And finally in codebehind in the Page_Load event:
ScriptManager.RegisterStartupScript(this, this.GetType(), tbContentHtml.UniqueID + "Add", "tinyMCE.execCommand('mceAddEditor', true,'" + tbContentHtml.ClientID + "');", true);
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), tbContentHtml.UniqueID + "Remove", "tinyMCE.execCommand('mceRemoveEditor', true,'" + tbContentHtml.ClientID + "');");
Not sure if you've looked at these.
http://joakimk.blogspot.com/2007/07/tinymce-inside-of-aspnet-ajax.html
and
http://codeodyssey.com/archive/2007/7/18/updatepanel-tinymce-demo-with-project-zip-file
Here is a tinymce forum post on it
http://tinymce.moxiecode.com/punbb/viewtopic.php?id=12682
Good luck.
You have to call the initializing method of the TinyMCE whenever the update panel is refreshed.
For this, you have either to call this method (tinyMCE.init) from a RegisterStartupScript method, or to create a page load javascript function in the head section of the page like this:
function pageLoad() {
tinyMCE.init();
}
This function will be executed each time the update panel is refreshed.
i solved this problem as
call tiny mce after the response generation of the ajax call
function edittemp(name) {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="edit_temp.php";
url=url+"?id="+name;
xmlhttp.onreadystatechange=stateChanged3;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged3()
{
if (xmlhttp.readyState==4)
{
spl_txt=xmlhttp.responseText.split("~~~");
document.getElementById("edit_message").innerHTML=spl_txt[0];
tinyMCE.init({
theme : "advanced",
mode: "exact",
elements : "elm1",
theme_advanced_toolbar_location : "top",
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,"
+ "justifyleft,justifycenter,justifyright,justifyfull,formatselect,"
+ "bullist,numlist,outdent,indent",
theme_advanced_buttons2 : "link,unlink,anchor,image,separator,"
+"undo,redo,cleanup,code,separator,sub,sup,charmap",
theme_advanced_buttons3 : "",
height:"350px",
width:"600px"
});
}
}
and the page caaled by ajax call is
<?php
$name=$_GET['id'];
include 'connection.php';
$result=mysql_query("SELECT * FROM `templete` WHERE temp_name='$name' and status=1");
$row = mysql_fetch_array($result);
$Content=$row['body'];
?>
<html>
<head>
<title>editing using tiny_mce</title>
<script language="..." src="tinymce/jscripts/tiny_mce /tiny_mce.js"></script>
</head>
<body>
<h2>change the template here</h2>
<form method="post" action="save_temp.php?name=<?php echo $name;?>">
<textarea id="elm1" name="elm1" rows="15" cols="80"><?php echo $Content;?></textarea>
<br />
<input type="submit" name="save" value="Submit" />
<input type="reset" name="reset" value="Reset" />
</form>
</body>
</html>
may be helpful in such situation.
I di this
<script language="javascript" type="text/javascript">
function pageLoad(sender, args) {
aplicartinyMCE();
}
function aplicartinyMCE() {
tinyMCE.init({
mode: "specific_textareas",
editor_selector: "mceEditor",
.....
});
}
</script>
That initialize the editor after each asynchronous postback even if
Then in page_load event
ScriptManager.RegisterOnSubmitStatement(this, this.GetType(), "salvarEditorMCE", "tinyMCE.triggerSave();");
TinyMCE (as well as other WYSIWYG editors, FCKEditor etc) suffers from postback validation issues. By default any ASP.Net page on postback has its contents checked, and any unencoded HTML throws the postback validation error.
Now many people, including on those forums suggest disabling the postback validation, validaterequest="false" , but this makes you susceptible to scripting attacks, the best thing to do is bind a function to the async postback event that fires off just before async postback. This JavaScript function needs to HTML encode the TinyMCE data being posted back to the server, this will then pass the postback validation and you'll be OK.
I believe TinyMCE and other editors correctly do this on postbacks but not async postbacks hence the issue, in fact if you look at TinyMCE's source you can probably find their function that does this and simply add the event binding.
Hope this helps

Categories

Resources