I created an adrotator in jquery for the first time and when I use it on a page that uses pagemethods to do ajax calls to the server and show a modal. The page posts back. When I remove the rotator the page works as it should. In the rotator I have the following code in the document ready function.
$(".animation_control a.play").live('click', function () {
$(this).removeClass('play');
$(this).addClass('pause');
Play();
});
$(".animation_control a.pause").live('click', function () {
$(this).removeClass('pause');
$(this).addClass('play');
clearInterval(timer);
});
$(".animation_control a.pause").click(function () {
});
//Toggle Teaser
$("a.collapse").click(function () {
$(".main_image .block").slideToggle();
$("a.collapse").toggleClass("show");
});
If I comment out this code the page stops the complete page refresh and and posts back async like it should. Any ideas on why this would cause the page to do a complete postback instead of a partial one?
As a guess, since the code is incomplete, you should add return false to your event handlers to prevent the links from actually firing.
.live('click', function (e) {
e.preventDefault();
//your code
Anchors are used to navigate to a page/region in the same page, and according to this part, clicking an anchor MUST move us to the HREF that the anchor is pointing to.
in order to cancle this default behavior, we will need to do either return false or to prevent the default action using jQuery.
This is an example of what i mean.
Related
I have a c# MVC page (not that I think that matters to this question). When the page is loaded, it immediately makes an ajax call to a service that prepares a lot of information, and then loads it into the page. (whilst displaying a Loading Data Modal).
<script type="text/javascript">
$(document).ready(function () {
$('#loadingWebServiceData').modal({
backdrop: 'static',
keyboard: false,
show: true
});
$("#Summary").load("/Summary/GetAllSummaries",
function () {
$('#loadingWebServiceData').modal('hide');
});
});
</script>
This all works when the page is first hit. However, if I then select a record, and make some changes to it on a different view, then save the changes, the last code in my controller is;
return View("Index");
This returns me back to my original page, however the data hasn't been updated. Debugger and breakpoints show that when I return to the index page the document.ready doesn't fire.
So either there is something subtly wrong in what I am doing, or I have misunderstood document.ready.
I have jquery tabs on my page, each tab has a single iframe in it. Everything works, except...
The iframes refresh each time I switch tabs.
The source for the Iframes is set in the Page_Load and is only executed once. The jquery does not do anything except change the tab...no other code.
Is there a way to not refresh the iframe each time?
This is why I never want to ask anything on this site...I know it's gonna be something simple, but for anyone that may be helped in the future from my pain...
In the code for the jquery tabs to select or hide tabs, I had a call to a button click event that was used to keep track of the current state of the tabs. This is what caused the postback and why my iframes were getting reinstantiated.
$(function () {
$("#tabs").tabs({
select: function (event, ui) {
var sel = ui.index;
$("[id*=SelectedTab]").val(sel);
$("[id*=ChangeTabButton]").click();
},
selected: $("[id*=SelectedTab]").val()
});
});
Thanks Kevin and Vishal...
I've got a mixture of JQuery and Ajax partial postbacks on a webforms page and I'm trying to stop the user navigating away from a page without their changes having been saved.
It's working pretty well unless one of the data validators on the page is invalid. There is a jquery method on the submit button that basically nulls the onbeforeunload event. In the event that the validators are invalid, I dont want that to happen, so I turned off the client side validation, and in the method, called Page.Validate(), then if the page was invalid, I tried to register a startup script as described here to reset like so:
if (!Page.IsValid) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "setConfirmUnload(true);", true);
return;
}
If I run the click submit and the page is invalid, the call to setConfirmUnload(true) happens, but the method cant be found (presumably because I re-set this up every time a postback happens?
The actual error is " JavaScript runtime error: 'setConfirmUnload' is undefined", possibly because the bindEvents() hasnt yet re-run and therefore created it?
I thnk my problem stems from the fact that I am using partial postbacks and autopostbacks, setting up data as the user modifies the form. By default that blitzes my jquery, so I rebind the jquery calls on document.ready() as well as on postback using
<script type="text/javascript">
// attach the event binding function to every partial update
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (evt, args) {
bindEvents();
});
</script>
And my Bind Events method looks like:
function bindEvents() {
// stuff removed for brevity here...
$(function () {
// Prevent accidental navigation away
$(':input, select').bind(
'change', function () { setConfirmUnload(true); });
$('.noprompt-required').click(
function () { setConfirmUnload(false); });
function setConfirmUnload(on) {
window.onbeforeunload = on ? unloadMessage : null;
}
function unloadMessage() {
return ('You have entered new data on this page. ' +
'If you navigate away from this page without ' +
'first saving your data, the changes will be lost.');
}
window.onerror = UnspecifiedErrorHandler;
function UnspecifiedErrorHandler() {
return true;
}
});
}
If that's the case, is there a way I can force the script to run after the bindEvents() call has happened?
I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work
I have page with other asp.net page inside iframe.
And on button click inside iframe i need to refresh main page from server side.
How can it?
Make use of javascript and you can easily do it
call the following function on your button click
<script language="javascript">
function RefreshParent()
{
window.parent.location.href = window.parent.location.href;
}
</script>
From the cs code if you are opening the aspx page in the iframe
Page.RegisterStartupScript("RefreshParent","<script
language='javascript'>RefreshParent()</script>");
Its explained very well in the following links:
link 1
link 2
Hope it helps.
For some reason the javascript function shown in earlier answers did not work for me (although the function was called). However, this worked for me:
function RefreshParent()
{
// Was: window.parent.location.href = window.parent.location.href;
parent.location.reload();
}
I had to add it near the start of my HTML (near the end of the HTML didn't work, as it was not yet rendered).
I used this C# code to call it, which is based on earlier answers but updated to use the current API which has an extra initial paramter, "type":
ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script language='javascript'>RefreshParent()</script>");