AddThis.com - ScriptManager - javascript

I am trying to register a JS file after a postback from an Update Panel. I am trying to get AddThis.com to work after a postback. It works if I set the multiview.activeviewindex equal to 1. However If I go from view 1 to view 2 it does not work.
Here is the server side code for the project.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'ScriptManager.RegisterStartupScript(Me, Me.GetType, "Test", "http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4d4c6a5604aba88b", False)
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType, "Test1", "http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4d4c6a5604aba88b", True)
MultiView1.ActiveViewIndex = 0
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MultiView1.ActiveViewIndex = 1
End Sub
Here is the ASPX code:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplication6._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4d4c6a5604aba88b"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:View>
<asp:View ID="View2" runat="server">
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style addthis_32x32_style">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
</div>
<!-- AddThis Button END -->
</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
I have tried registering the startup script on the scriptmanager.
Does anyone know how to get this working?
Thanks!

It looks like AddThis works only during window or document load and therefore a little trick is required here. Basically the idea is that you should render AddThis div on first view, than grab it into javascript field and than show inside a div provided in second view.
First of all you have to change your server side code, because you would like to include a whole file, not a script block. You should also do it during PageLoad method only (I'm using c# so that you have to rewrite call below).
ScriptManager.RegisterClientScriptInclude(this, GetType(), "Test", "http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4d4c6a5604aba88b");
You can also just put it in your html header (as you did) and get rid of ScriptManager call which is unnecessary in that case.
Than you have to change a content of your multiview a bit
<asp:View ID="View1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
<div style="left:-2000em; position:absolute;">
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" id="addThis">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
</div>
</div>
</asp:View>
<asp:View ID="View2" runat="server">
<div id='addHere'></div>
</asp:View>
To do this I wrote a simple javascript module which handle the task.
PageModules = {};
PageModules.AddThis = function ()
{
var $addThis;
function takeAddThis()
{
setTimeout(function ()
{
$addThis = $('#addThis');
$addThis.remove();
}, 100);
Sys.Application.remove_load(takeAddThis);
}
function fixAddThis()
{
var $addHere = $('#addHere');
if ($addHere.length)
{
$addHere.html($addThis);
}
}
Sys.Application.add_load(fixAddThis);
Sys.Application.add_load(takeAddThis);
} ();
Notice that PageModules plays only a namespace role to avoid messing up with a global scope. The AddThis module is self-initialized and it is a kind of singleton. Also you would need to reference jQuery or rework the body of inner methods. I have wrapped your AddThis div by additional "hidden" div to not show it to user. add_load method is fired after all scripts are loaded and after all objects are created according to msdn reference
http://msdn.microsoft.com/en-us/library/bb383829.aspx
We need takeAddThis to be fired only once so that I unbind this method after first call. Additional timeout shifts our logic to the end of queue which secure that AddThis logic would be properly executed (i could use $(document).ready from jQuery here as well, however I wanted to stay consistent.

Related

InvalidOperationException: WebForms UnobtrusiveValidationMode in C#

I've a web form with a text box and RequiredFieldValidator Control.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name : <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate ="TextBox1" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>
<asp:button runat="server" text="Button" />
</div>
</form>
</body>
</html>
When I load the page and click on the button, I get an error saying
Error:
[InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).]
System.Web.UI.ClientScriptManager.EnsureJqueryRegistered() +145
System.Web.UI.WebControls.BaseValidator.RegisterUnobtrusiveScript() +11
System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +88
System.Web.UI.Control.PreRenderRecursiveInternal() +166
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Control.PreRenderRecursiveInternal() +236
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4682
I did some googling and found some solutions like changing the target version to 4.0 in web.config, using jquery in the global.asax file and changing the property of UnobtrusiveValidationMode to none.
I even read about unobtrusive javascript at https://en.wikipedia.org/wiki/Unobtrusive_JavaScript. But I could not make any relation with the content given there and the error I encountered
Most of the answers said to refer http://connect.microsoft.com/VisualStudio/feedback/details/735928/in-asp-net-web-application-visual-basic-the-requiredfieldvalidator-doest-work
But this link no longer exists.
When I viewed the source of the web page after changing the target version to 4.0, I found some extra inline javascripts(I guess that's called obtrusive javascripts). What's wrong in using inline codes?
I'm pretty new to ASP.net, so little brevity appreciated.

How to reference multiple identical user controls on a page

I'm trying to use several instances of an ascx control on a single page. Only the last control on the page works. I understand from this post [Asp.Net User Control does not work correctly when multiple are added to one form that the problem is related to the IDs; somehow I'm trying to reuse the IDs and the specific control being edited is not referenced correctly. However, the code on that page is complex and I don't understand the answers. I created a small example of my problem to demonstrate.
Here is my user control:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="testControl.ascx.vb" Inherits="Tempusforms.testControl" %>
<script type="text/javascript">
function getValue() {
document.getElementById("<%=Label1.ClientID %>").innerHTML = getIndex();
}
function getIndex() {
return document.getElementById("<%=droppit.ClientID %>").selectedIndex;
}
</script>
<span>
<asp:DropDownList ID="droppit" runat="server" OnChange="getValue();" >
<asp:ListItem Value="Select a Value"></asp:ListItem>
<asp:ListItem Value="one"></asp:ListItem>
<asp:ListItem Value="two"></asp:ListItem>
<asp:ListItem Value="three"></asp:ListItem>
</asp:DropDownList>
</span> Index Value =
<span>
<asp:label ID="Label1" runat="server" Text="mylabel" ></asp:label>
</span>
Here is the page that uses the controls:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="userControlTest.aspx.vb" Inherits="Tempusforms.userControlTest" %>
<%# Register src="../Common/testControl.ascx" tagname="testControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:testControl ID="testControl1" runat="server" />
<br /><br />
<uc1:testControl ID="testControl2" runat="server" />
</div>
</form>
</body>
</html>
Can you show me how to make this work?
Thanks for your help.
ASP.NET generates different IDs which include the UserControl ID so IDs aren't the issue here.
However the problem is with the JS code that you are including in the User Control. This gets repeated and bad things happen because of that obviously.
You should get those scripts outside the User Control and change them to use parameters.
Something like:
<script type="text/javascript">
function getValue(ctrlID) {
document.getElementById(ctrlID).innerHTML = getIndex(ctrlID);
}
function getIndex(ctrlID) {
return document.getElementById(ctrlID).selectedIndex;
}
</script>
And you can call these functions from the User Control like this: OnChange="getValue(this.id);"

Access content page control from master page using javascript

I want to access the content page Ajax combobox control in the master page and that too by using Javascript.
I have been trying the same by using the contentpageholder of the content page, but also one of the problem I get is there are around 10 content pages, so when some other page like Page 1 is opened , the code show object reference exception as contentplaceholder is not matched.
How to get that which content page is opened up?
Also I am not able to get the code working to get the maincontentplaceholder id in master page.
What I have done till now:
function accessControlContentPage() {
var txtCont = document.getElementById("Page.Master.FindControl('ContentPlaceHolder1').FindControl('txtContent')").value;
var text=txtCont;
}
But this is not working.
Any help with the same?
The suggested approach is add a specific content place holder controls for such scripts to be placed in the web page you are rendering. Take a look at the following master/content page markup:
Master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApp.PageMethods.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
There is a content place holder head wherein I must write some js functions trying to access the dropdown list in the other content place holder ContentPlaceHolder1.
Content page markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApp.PageMethods.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script>
function foo() {
var ddl = document.getElementById('<%= DropDownList1.ClientID %>');
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</asp:Content>
Here I didn't have to worry so much about trying to access controls nested in ContentPlaceHolderID.
Alternatively, if you don't have that option/freedom, you can always write something as follows in your master page itself:
var d = document.getElementById('<%= this.ContentPlaceHolder1.FindControl("DropDownList1").ClientID %>');
Access content page control from master page using javascript
we can find div id or control id of content page from master page in asp.net
Explanation of content page:-
don't forgot to mention runat="server",
ContentPlaceHolderID="content_body" //observation,
main_content is the ID of div tag
MasterPage.master
var d = document.getElementById('<%= this.content_body.FindControl("main_content").ClientID %>');
Do whatever you want with d
Thank you

Perform at same time javascript and asp.net rendering

Suppose I have a .gif:
<img alt="" src="./wait.gif" />
And I have a Label:
<asp:Label ID="tbnotif" runat="server" ReadOnly="True" Text="" ></asp:Label>
And a button:
<asp:Button ID="Button1" runat="server" Text="Pubblica" OnClientClick="show_table();add_gif();" OnCommand="Button1_Click" />
I'm using aspx pages, the question is:
Can I click on the button and at same TIME show the .gif with JavaScript and change the Label from code behind? Or will things never be shown at same time?
It looks to me like you want to show a busy animated gif between postbacks, is that right?
Here's how I do it (unless I'm using update panels which have their own progress indicator server control)
<script type="text/javascript">
window.onbeforeunload = function(){showGif();};
</script>
When the page unloads because of a postback (click the button which POSTs to the server), reveal the gif image. When the new page comes back from the server the image will disappear because it's now a new page.
Changing a label is a small operation, so you will probably never see the image as the request/response will turn around very quickly. For testing you can add a System.Threading.Thread.Sleep(3000) in your button handler to simulate a longer running process.
EDIT
AJAX is your only option then, but there are many many ways. One possible solution:
Put the label in an UpdatePanel server control, place button outside of update panel, but set it as an AsyncPostbackTrigger in the update panel's declarative mark-up in the aspx page. Show the gif with OnClientClick handler client-side or using JQuery to attach a client-side click handler to the button.
aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="AjaxLabel._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="ajaxLabel">Initial value</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="asyncButton" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<img id="theImage" src="img/success.png" style="display: none;" />
<asp:Button runat="server" ID="asyncButton" Text="Client & Server Click" OnClientClick="showImage();" OnClick="asyncButton_Click" />
</div>
</form>
<script type="text/javascript">
function showImage() {
document.getElementById('theImage').style.display = "block";
}
</script>
</body>
</html>
aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AjaxLabel
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void asyncButton_Click(object sender, EventArgs e)
{
ajaxLabel.Text = "Server-side value";
}
}
}

JavaScript into Asp Page

i am learning javascript client side scripting language and i am using js in ASP.. i dont know when i compile the code, it shows
COMPILATION ERROR:Compiler Error
Message: CS1061: 'ASP.default_aspx'
does not contain a definition for
'popup' and no extension method
'popup' accepting a first argument of
type 'ASP.default_aspx' could be found
(are you missing a using directive or
an assembly reference?)
here is my code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WEB_test_app._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Shuraat Web ki</title>
<script type ="text/javascript">
function popup()
{
alert("popup!!");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick ="popup()"/>
<script type ="text/javascript">
document.write("Abid");
</script>
</div>
</form>
</body>
</html>
You're confusing client-side and server-side events. The popup() function is written in Javascript and runs on the client, but OnClick is a server-side event, so its handler runs on the server and has to be written in the language of your page (C#). popup() has no meaning in that context.
You can use the ClientClick event in order to handle the button click client-side. Note that you probably should return false from the handler in order to avoid a postback to the server:
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick ="popup(); return false;" />
You have to assign popup() to the event OnClientClick instead of Click like this:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick ="popup()"/>
The reasoning behind your problem is that when the run-time saw OnClick it tried to attatch that event with a C#/VB.Net (Code-Behind) method (which obviously does not exist) and we solved that by attaching the event OnClientClick to your Javascript method.
OnClick - is click handler on server side. If you want to call javascript function, use OnClientClick.

Categories