JavaScript code to refresh page and or telerik grid - c#

I need some kind of code which will refresh the page every 5min and if not the page then just the Telerik grid displayed on it since that's all that's rly needed.
Only other thing would be if it was after 5min of no activity on the page if possible but it's not core feature.

One possibility is to use a meta refresh tag:
<meta http-equiv="refresh" content="300" />
Another possibility is to use the window.setInterval method to send periodic AJAX requests to a controller action and update the DOM:
window.setInterval(function() {
// Send an AJAX request to a controller action which will
// return a partial with the grid and update the DOM
$.ajax({
url: '/grid',
success: function(result) {
$('#someGridContainer').html(result);
}
});
}, 300000);
And to implement the idle functionality you could use the jquery idle plugin.

keep it simple, call refreshGrid() function when you need to refresh grid.
function refreshGrid() {
if ($(".t-grid .t-refresh").exists()) {
$(".t-grid .t-refresh").trigger('click');
}
}
/*return true if does selected element exist.*/
(function ($) {
$.fn.exists = function () { return jQuery(this).length > 0; }
})(jQuery);

setTimeout(function(){
window.location.reload();
},300000);

If your grid is set up for ajax refreshes, then you can use something like
<script type="text/javascript">
$(function() {
setInterval(function() {
$('#GridName').data('tGrid').ajaxRequest();
}, 300000);
});
</script>

For Server Bindings Telerik Grid Just need to do the following Thing..... Just use and cheers
After any event you can call this
var href = $('.t-refresh').attr('href');
window.location.href = href;

If you are using Ajax or Webservice binding on the Telerik Grid, you can call the rebind() method on the grid object. That will force it to call the Select method of the binding again to get the latest data.
If you combine the rebind() call with Darin's answer of using the SetInterval method, it should give you what you are after.

Related

show loading Gif animation whenever page gets time too load

How can I show a loading Gif animation by using a jquery in asp.net project in Main.Master page? Whenever its taking time, I would like to show this Gif.
I searched on internet but they are showing this loading images for one control only. Thats why i need to keep this jquery at one place (ie: in master page) and want too use it on all content page whenever its taking too much time to load the page (either first time the page loads or button clicked or any event taking time)
$.ajax({
type: "POST",
url: "~/Jobs/ExportJobEntry.aspx",
data: dataString,
beforeSend: loadStart,
complete: loadStop,
success: function() {
$('#form').html("<div id='msg'></div>");
$('#msg').html("Thank you for your email. I will respond within 24 hours. Please reload the page to send another email.")
},
error: function() {
$('#form').html("<div id='msg'></div>");
$('#msg').html("Please accept my apologies. I've been unable to send your email. Reload the page to try again.")
}
return False);
});
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#loading").show();
}).ajaxStop(function () {
$("#loading").hide();
});
});
I used this code but it is not working
You can use jQuery BlockUI plugin. Here is official website, please read documentation
http://malsup.com/jquery/block/
You can do it like this
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
Then you can define $loading how ever you want

Trigger event in MVC Framework

As you've known, it's very easy to trigger an event in WebForm, but it's a problem in MVC Framework. For example, I have 2 DropDownList, Country and State. I want to load the data in State base on selected Country. In WebForm, I can trigger the SelectedIndexChange event, but in MVC Framework, what should I do?
Please help. Thanks in advance.
In WebForm, I can trigger the SelectedIndexChange event, but in MVC
Framework, what should I do?
You could use javascript and subscribe to the onchange javascript event of the dropdown.
For example if you use jQuery:
<script type="text/javascript">
$(function() {
$('#id_of_your_drop_down').on('change', function() {
// the value of the dropdown changed. Here you could do whatever
// you intended to do. For example you could send the selected value
// to a controller action using an AJAX call.
var selectedValue = $(this).val();
var url = '#Url.Action("SomeAction")';
$.post(url, { value: selectedValue }, function(result) {
// The AJAX request completed successfully. Here you could
// do something with the results returned by the server
});
});
});
</script>

Executing Server-Side Methods by Clicking on a DIV

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

.NET / jquery - previewing a form result/rendering a view to a string

Here's the situation (using MVC 2.0):
I'm trying to build a feature to allow a user to preview changes they make to their bio/profile without actually committing their changes first. User fills out a form, clicks a "Preview" button and see what their changes look like. One difficulty is the front-end has a different master-page, so we need to render the whole view, not just a control.
Here's the approach I took:
Asynch post the serialized form to a controller action
Manipulate the model to flesh out the collections, etc. that don't get posted
Return the front-end view, passing it this modified model
Catch the response to the asynch method, wrap it in an iframe and write that to a lightboxed div on the page
Code I'm using... Controller action (the BuildPreview method just alters the model slightly)
[HttpPost]
[Authorize]
public ActionResult PreviewProfile(PersonModel model)
{
return View("Person", PeopleService.BuildPreview(model));;
}
HTML/Jquery stuff:
<script type="text/javascript">
$(document).ready(function () {
$("#previewButton").click(function (e) {
$.post("/PreviewProfile", $("#bioForm").serialize(), function (response) {
$("#previewFrame").html(response);
$("#holdMyPreview").modal({
overlayClose: true,
escClose: true,
autoResize: true,
}, "html");
});
});
});
The modal method is just a basic lightbox-esque thing.
Running into two problems:
EDIT - removed this, I was accidentally pulling a child control
The iframe isn't rendering the html (perhaps because it's not valid b/c it's missing html/body/head tags?). If I just drop the response direcltly into the div, without the iframe, it works... albiet with the wrong stylesheet. If I try to insert it into iframe it just treats it as an empty page, just the html, head and body tags show up.
Any thoughts?
Sam
PS: Tried this over at MSDN forums (http://forums.asp.net/t/1675995.aspx/1?Rendering+a+view+into+a+string+) and it didn't get anywhere, figured I'd see if SO has any brilliance.
so, just massage the response when you get it back, add the missing html/body/head
$.post("/PreviewProfile", $("#bioForm").serialize(), function (response) {
response = "<html><body>"+response+"</body></html>";
$("#previewFrame").html(response);
$("#holdMyPreview").modal({
overlayClose: true,
escClose: true,
autoResize: true,
}, "html");
});

JQuery causing postback in .NET

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.

Categories

Resources