Reload event of ASP gridview - javascript

I am trying to fix some issues in an old asp.net application which uses ASP GridView. There are several events bound to the grid. Say sort, row click etc. I want to execute some js function after load/reload completes, (like after sort using header click etc.).
I tried
JQuery's ready function, which fires only on page load.
Placed a script block next to the grid
Placed a RegisterStartupScript in grid_sort (where DataBind happens)
none of them fires on grid reload after sort.

Server-side events always cause a full page lifecycle. But if there are UpdatePanels in the mix then you may get a partial page postback which won't trigger a page load event. Keep in mind the full page lifecycle happens regardless.
When you want to execute some client side code after handling some sort of server side event, you need a way to pass some information to the JS/jQuery after the page fully renders. Usually this is done by using 1 or more <asp:HiddenField> controls.
Typically I will set its ClientIDMode to static to make life easier on the JS side of things. So for example if you have this:
<asp:HiddenField ID="hfSomeData" runat="server" ClientIDMode="Static"
Value="Something set after handling some gridview event"
then you can do this on the javascript side to access the value:
$("#hfSomeData").val();
The following code will execute PostBackHandler based on either the jquery ready event or call from endRequest as issued by an UpdatePanel partial page update
// Handle Full Page postbacks
$(function () {
PostbackHandler(0);
});
// Handle Partial Page postbacks
// i.e. when Gridview embedded in an UpdatePanel
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function(sender, args){
PostbackHandler(1);
});
//PostBackType : 0 for Full Postback
// : 1 for Partial Postback
function PostbackHandler(PostBackType) {
var passed_in_data = $("#hfSomeData").val();
if (PostBackType === 0)
// do postback stuff
else
// do partial postback stuff
}

Related

Is there an event in an MVC 5 View or jquery raised when a partial view has been loaded and its elements are accessible

I have an MVC 5 view that acts as a parent view. Based on certain activities a user performs, I will load a partial view into the parent view. The partial view is loaded as part of a javascript function call. In my javascript call, I am loading my partial view with the content returned in the "data" variable below:
$.get(url, function (data) {
$('#id-ContainerForMainFormPartialView').html(data);
});
The data is written to an HTML div as follows:
<div class="container" id="id-ContainerForMainFormPartialView">
</div>
Immediately after the $.get call I run the following statement to disable a button that is part of the view that has been returned and written to the div:
$('#idAddLineItem').prop("disabled", true);
When the javascript function has completed the button is not disabled. Yet, I am able to disable the button using the same disable statement above using a button. I think that after the $.get invocation has written the partial view it is too soon to try and do something to any elements that are part of the partial view.
Is there an event I can hook into or something that will signal me when the time is right to try and do something to any of the elements of the partial view that has been loaded such as disabling a button which is what I am trying to do? Something like the javascript addEventListener() method that allows you to run code when certain events happen but in this case I need it to fire after a partial-view load is considered completely rendered and ready to use. An example would be greatly appreciated.
Thanks in advance.
Based on blex's statement the solution is as follows:
The correct way to disable a button that's part of a partial view being output:
// Correct Approach
$.get(url, function (data) {
$('#id-ContainerForMainFormPartialView').html(data);
$('#idAddLineItem').prop("disabled", true);
});
The incorrect way to disable a button that's part of a partial view being output:
//Incorrect Approach
$.get(url, function (data) {
$('#id-ContainerForMainFormPartialView').html(data);
});
$('#idAddLineItem').prop("disabled", true);
I originally had the disable statement outside the $.get call which allowed the code to run past it before the view was ready due to the asynchronous nature. Placing it inside the $.get allows it to not run until the partial view is done being output.

Call JavaScript function after Telerik RadPageView finishes loading?

I'm using Telerik UI for asp.net. Specifically I'm using RadTabStrip with partial page postbacks to allow the user to tab through different sets of data. When the user clicks a tab, some code executes and loads data just for that tab.
I've figured out how to execute codebehind: I set the OnTabClick property of the RadTabStrip, and then in codebehind I check what tab was clicked.
E.g.
protected void tab_Click(object sender, RadTabStripEventArgs e)
{
if (e.Tab.Text == "Info")
{
populateInfoTab();
}
}
private void populateInfotab()
{
// Do some stuff
}
However, I can't figure out how to execute client side javascript after a specific tab is clicked. What I tried:
Set OnClientTabSelected property, and then add some javascript:
function tab_ClientClick(sender, args)
{
var tab = args.get_tab();
if(tab.get_text() == "Info")
{
alert("Tab Clicked");
}
}
The problem is that I need to set the InnerHtml of some div in the clicked pageview after it is clicked. The div does not exist on page load (that specific RadPageView is hidden) so I cannot set it then. Once the user clicks into the tab, and after the page view loads, I need to be able to update the div's InnerHtml through JavaScript.
How would I go about doing this?
First option - if you do not set the RenderSelectedPageOnly property to true, all page views will be rendered on the initial load and you will be able to use JS to find/modify elements in them.
Second option - just set the content from the server as soon as you load the UC, this will usually make things simpler.
Third option - use client-side events (offered by the native PageRequestManager class or the RadAjaxManager, depending on how you setup your AJAX interactions) to execute when the response is received. The difficulty here is to determine which is the postback you need. Looking for the desired element and only executing logic if it exists is the simplest flag you can opt for.
Fourth option - register a script from the server code that will call your function, something like:
populateInfoTab();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "someKey", "myDesiredFunction()", true);
where you may want to use the Sys.Application.Load to ensure it is executed later than IScriptControl initialization.

asp validation controls not firing after ajaxrequest been called

Asp validation controls not firing after ajaxrequest been called.
I'm calling a function with below code to refresh a grid.
window['My Grid Client ID'].AjaxRequest('My Grid Unique ID', 'Rebind');
after Grid refreshed, validation not firing on click of submit button for the first time. for the next click it is working fine.
Hope this is due to ajax problem.!!
please respond if any one came across this scenario...
As you mentioned you are using Telerik. I would suggest you to rebind grid using below code instead of AjaxRequest, this will Rebind grid from ClientSide.
<telerik:RadCodeBlock runat="server">
<script type="text/javascript">
function refreshGrid() {
var grid = $find("<%=RadGrid1.ClientID%>");
var masterTableView = grid.get_masterTableView();
masterTableView.fireCommand("Rebind");
}
</script>
</telerik:RadCodeBlock>
For more help on this you could use below links
RadGrid Client side API
RadGrid Client object
This will not use any AjaxRequest to bind grid and will not affect any of your Validation functionality.
Hope this helps..!!!
What validation are you using? If it is custom validation and your JavaScript code is in the user control you load with the ajax request, this script will not actually exist in the browser. Wrap it in a RadScriptBlock control or use the ScriptManager.RegisterClientScriptBlock method to have it working on the page.
Also, make sure you have proper ValidationGroup settings for all your validators. If some submit buttons appear with AJAX this may break your existing page if you have no groups defined.

Multiple jQuery document.read event handlers running in wrong order

I recently added a feature to our ASP.NET MVC web application. There's a page that is displayed when the user clicks on an item in a table. The page uses AJAX to display a partial view in a single div in the page's HTML. The partial view uses the Telerik Kendo UI to define and display dialogs and DropDownList controls. This is complicated in that the JavaScript imports are all on the View for the page, while the PartialView just builds the HTML to be displayed in the div.
The JavaScript I wrote on the page includes a jQuery document.ready event handler:
$(document).ready(
function () {
if ( $('#details-map').val() != '' )
$('#details-map').remove();
var urlTail = '?t=' + (new Date().getTime());
// Make the AJAX call and load the result into the details box.
$('#detailsbox').load('<%= Url.Action("Details") %>' + '/' + '<%: Model.Id %>' + urlTail, displayDetails);
}
)
This works fine when I run the application on my localhost. The problem appears when I deploy the page to our development server. In this case, there's an additional document.ready event handler that's emitted to very end of the page by the Telerik Kendo / ASP.net MVC extensions:
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){
if(!jQuery.telerik) jQuery.telerik = {};
jQuery.telerik.cultureInfo=...;
});
//]]>
</script>
On this page, the $(document).ready event handler I wrote runs before the Telerik handler, and my code clearly depends on the Telerik handler running first. When mine runs first, I get a JavaScript error that says "jQuery.telerik.load is not a function'.
Since this does not happen on my localhost, how do I make sure that the second document ready event handler is run first?
Edit:
After more research, I've found that the problem is that the two scripts mentioned in my answer, which are supposed to be written to the page via the following line in the Master Page used by my page:
<%= Html.Telerik().ScriptRegistrar().Globalization(true).jQuery(false).DefaultGroup(group => group.Combined(false).Compress(false)) %>
Are not being loaded. In other words, the above line does nothing. It works on another page that uses the same Master Page, though. I've placed a breakpoint on the line and it is executing. Does anyone have any ideas?
You're either going to have to make it show up after the second one on the page OR do something I hate to suggest:
$(document).ready(function() {
function init {
/* all your code that needs to be run after telerik is loaded */
}
if ( $.telerik ) {
init();
} else {
setTimeout(function check4telerik() {
if ( $.telerik ) {
return init();
}
setTimeout(check4telerik, 0);
}, 0);
}
});
So, if $.telerik is loaded, it runs, otherwise it polls until it's set, and when it is set, it runs the code. It's not pretty, but if you don't have more control, it's probably your only option, unless $.telerik emits some kind of event that you can hook into.
After spending a few hours working on this, I finally got it to work. The problem turned out to be that two JavaScript files that are used by the Telerik DropdownList control and Window control were not being loaded.
In spelunking through the JavaScript on the page, I came across this script that was generated by Telerik:
if(!jQuery.telerik){
jQuery.ajax({
url:"/Scripts/2011.3.1306/telerik.common.min.js",
dataType:"script",
cache:false,
success:function(){
jQuery.telerik.load(["/Scripts/2011.3.1306/jquery-1.6.4.min.js","/Scripts/2011.3.1306/telerik.common.min.js","/Scripts/2011.3.1306/telerik.list.min.js"],function(){ ... });
}});}else{
jQuery.telerik.load(["/Scripts/2011.3.1306/jquery-1.6.4.min.js","/Scripts/2011.3.1306/telerik.common.min.js","/Scripts/2011.3.1306/telerik.list.min.js"],function(){ ... });
}
This script was emitted by a call to Html.Telerik.DropdownListFor() in my partial view. I'm guessing that the code to include for the two JavaScript files mentioned in the code, telerik.common.min.js and telerik.list.min.js, was not emitted since the call was on a partial view. Or I was supposed to include them all along & didn't know it (I'm very new to these controls). Oddly, everything worked when I ran it locally, so I don't get it.
In any case, I added two <script> tags to my View to include these files and everything started working. That is, I added the following tags to my page:
<script type="text/javascript" src="../../Scripts/2011.3.1306/telerik.common.min.js"></script>
<script type="text/javascript" src="../../Scripts/2011.3.1306/telerik.list.min.js"></script>
Live and learn.

Running javascript whenever UpdatePanel refreshes

I am using an asp.net update panel to refresh the content on a page when a menu item is selected.
Within the content that is updated are images which have a javascript reflection function which is triggered with the following line of code:
window.onload = function () { addReflections(); }
This runs fine when the page is first loaded but not when a menu item is selected and the update panel is run.
On previous projects using jquery code I have replaced document.ready with function pageLoad but there is no document.ready on this page.
Like this:
<script>
// ASP.NET AJAX on update complete
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function(sender, args) {
// your code here, eg initToolTips('/Common/images/global/popup3.gif');
});
Basically, it's because that event isn't triggered by an update panel refresh.
There are ways to achieve this behaviour though, Ajax.Net has an EndRequestHandler function that you can hook into.
Here's a good example:
http://zeemalik.wordpress.com/2007/11/27/how-to-call-client-side-javascript-function-after-an-updatepanel-asychronous-ajax-request-is-over/
i think u should use
function pageLoad(sender, arg) {
if (!arg.get_isPartialLoad()) {
// in first load only
}
//every time the update panel refreshed
}
Regards
Take a look to this event:
http://msdn.microsoft.com/en-us/library/bb383810.aspx
window.onload is fired when the entire page is loaded. UpdatePanel uses an AJAX approach, so whenever it's updated and round trip ends, the page remains loaded and only a portion of this has been updated.
In other words, you need to do that "when a request to the server ends".

Categories

Resources