I have a commenting system which is working well. I need to create an admin panel but for the time being I just want to have an asp.net page which auto loads every (n) seconds and shows me the latest posts from the post table. Its very simple (in concept). Anyone with some good links/pointers?
Onload, start a javascript timer that refreshes the page after n seconds. Alternatively, you could put the data in an update panel and have the javascript update the updatepanel every n seconds, but then you would need to create a loop to call the javascript repeatedly, every n seconds.
I would suggest looking into the setTimeout/setInterval functions in Javascript that will call a specific function after the time has elapsed. In your case this will be an AJAX call to an ASPX page and then (i'm assuming) you'll want to fire the result into a DIV somewhere in your page...
setInterval(function(){
$.ajax({
url: 'test.aspx',
success: function(data) {
$('#myDiv').html(data); // fill div with response
}
});
}, 5000); // call after 5 secs
Something along those lines is roughly what i think you're after, although it is untested!
Cheers
Stuart
Related
I have a page that is processing data. It goes through a series of 10 steps. I want the page to display a status after each step. ie. after step 1 data processing done print "Step 1 done" then after step 2 data processing done add text "Step 2 done" etc. How can I do this using only C# without hard postbacks? Or do I have to use AJAX/Javascript or page postbacks?
I've been playing around with updatepanels. One around the whole set of steps. Or an updatepanel around each step and then calling button clicks pro grammatically. The only result I can get is for all the text to display at one time at the end of processing.
I've been racking my brain and have search google endlessly. Hopefully someone out there has an idea for me. Thanks!
I'd suggest using ajax -
Server Side:
up a new action method on your server (assuming it's MVC), use this action method to query the state of the task.
public string QueryStatus()
{
return Session["progress"].ToString();
}
When the task progresses to the next step, update a variable to indicate this (in database, or session).
Session["progress"] = "Step Four";
Client Side:
Periodically call the action method and update an element on the page accordingly.
<script>
$.ajax('/Server/QueryStatus').done(function(response)
{
$('#progressElement').innerHTML = response;
})
</script>
EDIT
Figured it out.. $.ajaxSetup({ cache: false }); wasn't working because i had data-ajax set to turned off on the form and therefore i wasn't able to set no cache ajax on it.. just for completeness if anybody knows how to get this done WHILE dada-ajax is set to false then please post so here
Something else that I just tried and it worked was to simply add data-ajax="false" to any link that you want a page refresh on. Meaning that if I have data-ajax="false" on a link it will always refresh the page before showing it!
For example the link I had a problem with was
Add a new weekly update
and the problem was that for some reason that page was caching and always showing the cached page.. So one of the easy fixes was to add data-ajax="false" to it and that forced a reload of the page everytime
Add a new weekly update
````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
Question:
I have a options menu which brings up a form which also has a cancel and submit button.
Once the form is submitted there is certain validation that runs and if something is missing it returns to the form with some validation text.
Now if I click the cancel button at anytime i should be brought back to the options menu and if I click on the same button that brings up the form i should see a brand new clean form and this works fine if I do it before the validation.
The problem is that if I submit a non valid form which returns with the error validation messages and THEN press cancel it seems that the page becomes cached or something similar because from that point on anytime I click on the form options menu button the same form shows up each with the validation errors and data. I put a break point in the method that returns the form View() and they are never hit so for some reason it skips the entire method which creates a new form and somehow just shows the old page.
The cancel button is the following
Cancel
Does anybody know what is happening? is it being cached somehow when it returns to the same page with the validation errors??
** EDIT **
I Tried adding [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] in front of the controller by to no avail..
I also now added
$.ajaxSetup({ cache: false });
to the top of my $(document).ready(function () but that also does not seem to be doing anything, do I just put it there or do I have to call it somehow?
I checked System.Web.HttpContext.Current.Cache and the page doesn't show up there.
Have you tried setting the output cache options on the controller action like
[OutputCache(Duration=600,VaryByParam="id")]
You might also want to try making sure jquery is not caching the request as well. You can globally turn off jquery ajax caching using the information here: How to set cache: false in jQuery.get call
You can try using $.mobile.changePage() to transition to the page, it allows you to set some options, one of which is reloadPage.
reloadPage (boolean, default: false) Forces a reload of a page, even if it is already in the DOM of the page container. Used only when
the 'to' argument of changePage() is a URL.
Source: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You could work this into your link with something like:
<script>
function changeMyPage(url) {
$.mobile.changePage(url, { reloadPage : true });
}
</script>
Cancel
jquery Mobile pulls multiple pseudo-pages into the DOM at one time and normally deletes (.removes()) a pseudo-page after you've navigated away from it. It however sounds like that's not happening so you may need to use my above code (or something similar) to force a refresh of the page.
You need to clear your ModelState before hand.
This should work:
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
**ModelState.Clear();**
return View(new CategoryViewModel());
}
}
How to Clear model after submit the data in database in MVC3
I have a function inside my .aspx.cs code which takes wuite a long time to do the processing until when I want to display a cool loading animation. I looked some of the earlier posts but either these didn't work for me, or were having solution specific to Page loading scenario (not loading a while a function completes).
I guess the right approach would be to fire a Javascript startLoader() function just before the the main function starts (which takes a long time), and then call a stopLoader() from the .aspx.cs itself to stop the loader when the function ends. Any suggestions how to implement this?
Yes, I've done this in ASP.NET Web From (not a ASP.NET MVC solution). You need to provide OnSubmit client side event handler. It basically break down to three parts: Javascript, HTML Div, and one line code behind:
Javscript:
function ShowLoading(e) {
// var divBg = document.createElement('div');
var divBg = document.getElementById('blockScreen');
var divLoad = document.createElement('div');
var img = document.createElement('img');
img.src = 'images/ajax-loader.gif';
divLoad.setAttribute("class", "blockScreenLoader");
divLoad.appendChild(img);
divBg.appendChild(divLoad);
document.getElementById('blockScreen').style.display = 'block';
// These 2 lines cancel form submission, so only use if needed.
//window.event.cancelBubble= true;
//e.stopPropagation();
}
function HideLoading() {
//alert('hideloading');
document.getElementById("form1").onsubmit = null;
document.getElementById('blockScreen').style.display = 'none';
//alert('done');
}
Add following DIV
<div id="blockScreen" class="blockScreen" style="display:none"> </div>
Finally, add the following to Page_Load in code behind.
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "submit", "ShowLoading()");
Now, all of your page postbacks are essentially have to call onsubmit event. It will display the animation before the page postback finishes.
if you really want to do, then the only way is webworkers. You've probably heard about them, or if not, i seriously recommend to have a look.
Yes, fire startLoader() on OnCliencClick of your button or whatever element you are using to fire the server-side event and call stopLoader() from the server-side at the end of your process. Something like this:
//rest of the server-side code above ...
Page.ClientScript.RegisterStartupScript(this.GetType(), "someKey", "stopLoader();", true);
If you don't mind that the browser is not responsive in the meantime, the simplest way of doing this is using an animated gif:
Activity indicators
ajaxload.info
webscriptlab
The trick is showing the image when starting your processing, and hiding it when finished. You can show it in an img, and use jQuery or whatever you want to show/hide it.
If you need the browser to keep responsive, use Web Workers. But be aware that some of the older browsers don't support it. See this reference
I've got a master page that contains this code at the bottom of the page:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(parseData);
</script>
</form>
the parseData() function I'm creating inside the main page and I'm adding functions to it based on each page load. parseData IS called after every AJAX refresh, but it appears to only call the contents of the function from BEFORE the request. If I hit F5 to refresh the page again, it will properly call all of the newly added content in the parseData function.
Does this function cache that data? How can I make sure it calls the newly created contents of the parseData function?
According to the research I did, this is a problem with MS AJAX UpdatePanels and you are really better off not using them. I revised my JavaScript to pull data from hidden form fields instead so the JavaScript functions never changed and was able to get this working.
if users press the browser's back button to reach the prior page, the page should display a message like "web page expired".
can i use javascript for this???
for example:
there are 4 pages in web sites. on page 1,2 and 3 the user can use the back-button, wheras on the 4th page the user gets the desired message.
i thought that i can do this by using counter.
i used following javascript on the master page ..
<script type="text/javascript">
function GoBack() {
window.history.go(+1);
}
</script>
and call the function in body like this:
<body onload="GoBack();">
and on the 4th page_load i do the following:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
it is working for all pages .. but i want to do this only for the 4th page
If you only want it on that page level, and when you use postbacks, then I suggest you simply keep it in ViewState instead of Session state. Session's also still available on other pages, where you might want to have other counters.
You need to keep the variable alive across requests. So one way is to put it in some viewstate or sessionstate. Sessionstate is least preferred. But you can possibly put it in a hidden textbox in the page and simply use it.
Looking at the problem after the much awaited update/edit, I shall suggest you to use SessionState. Please give a try on it.