Facebook Like button not rendering inside a reloaded GridView - asp.net

I have a fb:like button inside the GridView and GridView is inside the update panel. The first time of page load the fb:like button showing but when we click the next button, on the next page the fb:like button doesn't render. Any idea what's wrong?

Due to the fact that you are updating the page with an update panel, the like button will not be rendered when only part of the page is updated. You will have to attach to the clientside updated event (in JS) and then trigger the Facebook XFBML render command:
FB.XFBML.parse();
more about this here:
http://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/
You can do this using the following code:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
var _panels, _count;
function pageLoaded(sender, args)
{
if (_panels != undefined && _panels.length > 0)
{
for (i=0; i < _panels.length; i++)
_panels[i].dispose();
}
var panels = args.get_panelsUpdated();
if (panels.length > 0)
{
updateFbLike();
}
}
function updateFbLike()
{
FB.XFBML.parse();
}
</script>
this is taken from this article:
http://msdn.microsoft.com/en-us/magazine/cc163413.aspx

Richard's solution worked fine for me. I shortened the code to:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandlerBerliner);
function EndRequestHandlerBerliner(sender, args) {
if (args.get_error() == undefined) {
FB.XFBML.parse();
}
}

Related

Mouse middle button does not work

i have a gridview which contains a linkbutton with a ID LnkCourseName
i have requirement that on a click of Middle button of a mouse a new tab should open.
to check the which button of a mouse got clicked, i used a javascript function as :
<script type="text/javascript">
function buttonalert(event) {
var button;
if (event.which == null)
button = (event.button < 2) ? leftclickclear() :
((event.button == 4) ? middleclickclear() : rightclickclear());
else
button = (event.which < 2) ? leftclickclear() :
((event.which == 2) ? middleclickclear() : rightclickclear());
dont(event);
}
function leftclickclear() {
$('#<%=HdUrl.ClientID %>').val("left");
}
function rightclickclear() {
$('#<%=HdUrl.ClientID %>').val("right");
}
function middleclickclear() {
$('#<%=HdUrl.ClientID %>').val("middle");
}
function dont(event) {
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
</script>
But on a press of a middle button i get an error
javascript:__doPostBack('dnn$ctr538$ViewTC_TakeAClass$GrdCourseDetail$ctl02$LnkCourseName','')
on a new tab url. Thanks for assistance.
This should be standard behaviour for any reasonable browser, and isn't really an ASP.NET or script issue - the problem is that you're using a link button, which will do a postback just like a button (i.e. <input type=submit>), and it's not a link as in an default a element.
If your links are really just that, and are not expected to post back to the server to execute some logic, and instead just specifies a URL to link to, then use a HyperLink control instead.

sender._postBackSettings.sourceElement is undefined

This is what I'm trying to do -
Using jQuery when the document is ready and if the page is not postback I issue a manual postback for an updatepanel to retrieve data from a database.
While the updatepanel is getting the data I present an updateprogress which I hide when the specific updatepanel finishes. I also want to "BLOCK" the screen from any interaction. After the data is loaded I have additional buttons on the form and I want to block everything in case of any partial-postback.
Here is the code:
$(document).ready(function ()
{
if(<% =(Not Page.isPostBack).ToString().ToLower() %>)
{
__doPostBack('upShipping');
}
}
function pageLoad() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
}
function BeginRequestHandler(sender, args)
{
$('.blur').css("display", "block");
if (args._postBackElement.id == 'upShipping') {
$get('divCalculating').className = 'Show';
}
}
function EndRequestHandler(sender, args)
{
$('.blur').css("display", "none");
if (sender._postBackSettings.sourceElement.id == 'upShipping')
{
$get('divCalculating').className = 'Hidden';
}
}
If I do not "CLICK" on the screen everything works great. But if I just click anywhere on the screen while the updatepanel updates the "EndRequestHandler" doesn't fire and I'm stuck with the loading gif and blocked screen.
I get the following error in the error console of the browser: sender._postBackSettings.sourceElement is undefined
Any ideas?
Thanks!
Nick
For some reason sender._postBackSettings.sourceElement kept coming back as NULL in the EndRequestHandler.
I defined a global var, assigned it a value at the BeginRequestHandler and checked its value instead in the EndRequestHandler.
This solved the problem.

In Chrome ajax async postback end does not work

I have a sample app developed in asp.NET 3.5. On my master page I use following code to display an GIF while loading the page. It works correctly on IE and FF, but fails in Chrome. On pressing the submit button, the server gets the request and completes its processing and while that is happening the browser shows the loading GIF as expected.However the postback never completes and user keeps on looking at the progress GIF. I wonder where I have goofed up... Pls help!
// Get the instance of PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Add initializeRequest and endRequest
prm.add_initializeRequest(prm_InitializeRequest);
prm.add_endRequest(prm_EndRequest);
// Called when async postback begins
function prm_InitializeRequest(sender, args) {
// get the divImage and set it to visible
var panelProg = $get('divImage');
if( panelProg != null)
{
panelProg.style.display = '';
// Disable button that caused a postback
$get(args._postBackElement.id).disabled = true;
}
}
// Called when async postback ends
function prm_EndRequest(sender, args) {
// get the divImage and hide it again
var panelProg = $get('divImage');
if(panelProg != null)
{
panelProg.style.display = 'none';
$get(sender._postBackSettings.sourceElement.id).disabled = false;
}
}
My divImage is simple
<div id="divImage" style="display: none">
<img id="imgId1" src="../../App_Themes/Images/progressbar.gif" style="border-width:0px;" />
<br />
Please wait...
</div>
Add the following script to your page.
<script type="text/javascript">
Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
if( navigator.userAgent.indexOf( 'WebKit/' ) > -1 )
{
Sys.Browser.agent = Sys.Browser.WebKit;
Sys.Browser.version = parseFloat( navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
Sys.Browser.name = 'WebKit';
}
</script>
See more at: http://blog.joeydaly.com/uncaught-sys-scriptloadfailedexception-sys-scriptloadfailedexception
I have problems with ajax in Chrome in my dev environment(localhost without a .something domain). When I switch to acceptance Chrome works fine. In what environment are you working?
What you could try is change the dev url in your host file to something with an extention.

asp.net external JavaScript file doesn't find Control.ClientID

On load I'm both calling a JavaScript setTimeout() function that will hide a .NET Panel control, and hiding it in the code behind on first load. Clicking the save button will set the Panel to visible then reload the page at which point a setTimeout() function is called... so basically you click save, and see a panel with "Details Saved" for three seconds, at which point it disappears.
The problem is the external JavaScript file can't find _pDivAlert.ClientID (I've debugged and it returns null). It only works when the code is in a tag in the .aspx page. Any suggestions as to how I can either pass the client ID to the HideControl() function or find the ClientID from the external JS file?
Here's my code, any suggestions?
<script language="javascript" src="Forms.js" type="text/javascript"></script>
<body onload="ToggleAlert()">
<form id="form1" runat="server">
<script type="text/javascript">
//alert the user that the details were saved
function HideControl() {
var control = document.getElementById('<%=_pDivAlert.ClientID %>');
if(control != null)
control.style.display = 'none';
}
function ToggleAlert() {
setTimeout("HideControl()", 3000);
}
</script>
I've also tried sending the ClientID within the ToggleAlert() call, but that didn't work:
<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')">
External JS:
function HideControl(_c) {
var control = _c;
if (control != null)
control.style.display = 'none';
}
function ToggleAlert(_c) {
setTimeout("HideControl(_c)", 3000);
}
can you show your markup with the panel and the codebehind where you hide it?
there's a difference between setting the Visible property to false and setting the style display attribute to none- the first will not render the element at all, meaning there isn't anything rendered with the id you're looking for.
edit: it's probably because of the way you're calling HideControl in the timeout- this should be a function instead of a string.
try doing
function ToggleAlert(_c) {
setTimeout(
function () {
HideControl(_c);
}, 3000);
}
just for clarity, when you pass a string to setTimeout, it's evaluated and then run. the code chunk that eval produces will run in a different scope than your ToggleAlert method, and so _c won't be available at that time.
edit: you also need to actually get a reference to the control. you're passing the id string to ToggleAlert, which relays it to HideControl, which is expecting an object not a string.
function HideControl(_c) { // _c is the id of the element
var control = document.getElementById(_c);
if (control != null)
control.style.display = 'none';
}

ASP.NET: Scroll to control

I've got a particularly large form in an page. When the form is validated and a field is invalid, I want to scroll the window to that control. Calling the control's Focus() doesn't seem to do this. I've found a JavaScript workaround to scroll the window to the control, but is there anything built into ASP.NET?
Page.MaintainScrollPositionOnPostBack = False
Page.SetFocus(txtManagerName)
Are you using a Validation Summary on your page?
If so, ASP.NET renders some javascript to automatically scroll to the top of the page which may well override the automatic behaviour of the client side validation to focus the last invalid control.
Also, have you turned client side validation off?
If you take a look at the javascript generated by the client side validation you should see methods like this:
function ValidatorValidate(val, validationGroup, event) {
val.isvalid = true;
if ((typeof(val.enabled) == "undefined" || val.enabled != false) &&
IsValidationGroupMatch(val, validationGroup)) {
if (typeof(val.evaluationfunction) == "function") {
val.isvalid = val.evaluationfunction(val);
if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
ValidatorSetFocus(val, event);
}
}
}
ValidatorUpdateDisplay(val);
}
Note the call to ValidatorSetFocus, which is a rather long method that attempts to set the focus to the control in question, or if you have multiple errors, to the last control that was validated, using (eventually) the following lines:
if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
ctrl.focus();
Page_InvalidControlToBeFocused = ctrl;
}
To get this behaviour to work, you would ideally need to ensure that all your validators are set to be client-side - server side validators will obviously require a postback, and that might affect things (i.e. lose focus/position) - and setting MaintainScrollPositionOnPostBack to true would probably cause the page to reload to the submit button, rather than the invalid form element.
Using the server side .Focus method will cause ASP.NET to render out some javascript "on the page load" (i.e. near the bottom of the page) but this could be being overriden by one of the other mechanisms dicussed above.
SO I believe the problem is because I was trying to focus on HtmlGenericControls instead of WebControls.
I just ended up doing a workaround based off of:
http://ryanfarley.com/blog/archive/2004/12/21/1325.aspx
http://www.codeproject.com/KB/aspnet/ViewControl.aspx
...in the interest of time.
public static void ScrollTo(this HtmlGenericControl control)
{
control.Page.RegisterClientScriptBlock("ScrollTo", string.Format(#"
<script type='text/javascript'>
$(document).ready(function() {{
var element = document.getElementById('{0}');
element.scrollIntoView();
element.focus();
}});
</script>
", control.ClientID));
}
Usage:
if (!this.PropertyForm.Validate())
{
this.PropertyForm.ErrorMessage.ScrollTo();
failed = true;
}
(Although it appears Page.RegisterClientScriptBlock() is deprecated for Page.ClientScript.RegisterClientScriptBlock()).
Adding MaintainScrollPositionOnPostback is the closest that ASP.NET has built in, but won't necessarily jump to the invalid field(s).
<%# Page MaintainScrollPositionOnPostback="true" %>
Very simple solution is to set the SetFocusOnError property of the RequiredFieldValidator (or whichever validator control you are using) to true
Are you sure Focus() won't do what you're describing? Under the hood, it is essentially doing the "JavaScript workaround" - it writes some JS to the page which calls focus() on the control with the matching ID:
Whichever control had Focus() called last before the page finishes processing writes this to the page:
<script type="text/javascript">
//<![CDATA[
WebForm_AutoFocus('txtFocus2');//]]>
</script>
Please insert these into your OnClick event
Page.MaintainScrollPositionOnPostBack = false;
Page.SetFocus("cliendID");
// or
Page.setFocus(control);
You should looks into jQuery and the ScrollTo plugin
http://demos.flesler.com/jquery/scrollTo/
I've achieved something similar using basic HTML fragments. You just leave an element with a known ID:
<span id="CONTROL-ID"></span>
And then either via script, on on the server side change the url:
window.location += "#CONTROL-ID";
In the first case the page won't reload, it will just scroll down to the control.
Paste the following Javascript:
function ScrollToFirstError() {
Page_ClientValidate();
if (Page_IsValid == false) {
var topMostValidator;
var lastOffsetTop;
for (var i = 0; i < Page_Validators.length; i++) {
var vld = Page_Validators[i];
if (vld.isvalid == false) {
if (PageOffset(vld) < lastOffsetTop || lastOffsetTop == undefined) {
topMostValidator = vld;
lastOffsetTop = vld.offsetTop;
}
}
}
topMostValidator.scrollIntoView();
}
return Page_IsValid;
}
function PageOffset(theElement) {
var selectedPosY = 0;
while (theElement != null) {
selectedPosY += theElement.offsetTop;
theElement = theElement.offsetParent;
}
return selectedPosY;
}
Then call ScrollToFirstError() in your OnClientClick of the button that is saving, make sure the button has CausesValidation=true as well.
There you have it.

Resources