Since I have just started working in IT (internship started about 2 months ago) I will try to give you all the information you need to help me out.
I have a MVC4 Application that uses LongPolling to receive new data (in my case messages) from a server. Depending on the kind of the message, it will treat it differently on the client-side.
One kind of these messages are system messages:
I have two views. One view has a button, the other has just some text.
A click on the button then
sets some Properties in the controller and
forces a page reload on the other view, resulting in new content (e.g. some text boxes)
Now, if I have opened these two views in a new window, it will work out just fine (in Firefox, IE and Chrome).
But if I have opened them in a new tab, it will only work in IE and Chrome. Firefox will receive the message, but it won't invoke the callback method.
$(document).ready(function () {
ReadChat();
})
This initializes the first call to ReadChat().
As I mentioned earlier, it works perfectly fine in tabs in IE and Chrome, but only in new windows in Firefox.
If I check with FireBug, the response from the server arrives and I can look inside the JSON. It just doesn't invoke the callback for some reason.
My first thought being that not everything is loaded yet, I added a timeout to the first call.
If I write it like this:
$(document).ready(function () {
setTimeout(ReadChat, 1000);
}
it also works in Firefox, as long as I do not set it lower than ~1000.
Has anyone come across the same problem? Why does Firefox make a difference here?
EDIT:
function ReadChat() {
$.fn.messaging({
receiveURL: '#Url.Action("myAction", "myMethod")',
myID: '#Model.myID',
callback: function(data) {
$.each(data.messages, function(k, v) {
if(v.kind == 3) {
location.reload(true);
}
});
ReadChat();
}, timeout: 25000
}, 'read');
}
Inside $.fn.messaging, the function for read will be called with the given parameters:
$.post(receiveURL, { id: myID }, function(response) {
if($.isFunction(settings.callback) {
settings.callback(response);
}
}
EDIT2:
As Diesel337 said, I'm now using
$(this).ready(function () {
ReadChat();
});
Opening in new tab:
Having made this adjustment, I tested it a bit more and at first glance it worked perfectly. Then i noticed, that if i click on the View, that should be reloaded, before clicking the button, it won't work. (The message is received, but the callback function not called)
On the other hand, if i ignored the View, that should be reloaded, and directly clicked the button, the page would reload without a problem.
It sounds really weird, i know, but if i don't look at the View, before clicking the button, it works.
I have also filed a new bug report on bugzilla about this.
Turns out it was not Firefox that was causing this problem but Firebug.
I tried to reproduce this error today once again and luckily had Firebug not active, so it worked like a charm.
After turning it on again to get any information on why this is, i got the same error.
Note: if you're developing something that requires an AJAX call on $(document).ready() better don't activate Firebug, because it will mess it up for some reason.
Have you tried to use $(this) instead of $(document) ?
$(this).ready(function() {
ReadChat();
});
OR
$(function() {
ReadChat();
});
Related
Does anybody know how to open an URL in a new tab from C# code?
I have tried with
Response.Write("<script type='text/javascript'>window.location.href('../Documents/doc.pdf','_blank'); </script>");
Response.Write("<script type='text/javascript'>window.open('../Documents/doc.pdf','_blank'); </script>");
Response.Write("$('#pageContent_Send').click();");
with
$("#pageContent_Send").click(function () {
window.open("../Documents/doc.pdf");
return false;
});
and it did not work, using "window.open" I get an "Pop-up Blocker" browser warning.
There are a few options for opening a new tab that won't get blocked.
You can have it open the URL with an anchor click, like so click me
You can submit a form to a blank target, giving a similar result, but from a form. This is useful if you need to post, but can also be useful for get. Like so <form method="get" action="<your destination>" target="_blank"><button type="submit">Click Me</button></form>
You can use JS with window.open but it has to be tied to an active click event. I see in your original post that this got blocked, but if you're triggering it on a click event directly (i.e. not using a setTimeout or an async call or something else that delays the window opening) then this should work in all browsers. Since you're trying to "fake" it by forcing a click, the browser is going to block this every time unless you explicitly allow it.
<a href='www.xyz.com' target='_blank'>Click me to open me in new tab</a>
I am using MVC2 and VS2010.
We have created a web application but want to stop any browser re-visiting pages after the page has been left.
We want to do this so that someone who is using a public computer who then leaves can feel safe. We dont want the scenario that a following user can just use the back button to view the first uses pages.
I have tried [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
This seems to work fine and I get a Web Page Expired. But if I press the browser back button again, the page will be displayed.
I have quite a similar situation myself in wanting to prevent a browser back situation and have researched a few different solutions. The first and worst being a Java script function which takes the user back to the page they were on if they click the back button in the browser. It hides the problem rather than solving it but thought id mention it. The code as follows:
<script type="text/javascript" language="javascript">
function disableBackButton() {
window.history.forward()
}
disableBackButton();
window.onload = disableBackButton();
window.onpageshow = function (evt) { if (evt.persisted) disableBackButton() }
window.onunload = function () { void (0) };
</script>
This works for Firefox, Chrome and IE ok. You can just put this in your master page.
Many people will tell you this is not the way to do things however as it intrudes on the well known browser behaviour etc etc
So my second suggestion is something I have seen here:
Disable browser cache for entire ASP.NET website
Which will not cache anything which is more inline with what you are wanting I think.
Another idea would be to pass a page or session token around and on actions check the token - if its invalid reroute to an error page. That would at least prevent a new user doing anything with the previous page.
Id be interested to know how you solved this, if you have solved it.
I have a web page that contains a textbox and a submit button. When the user edits the text in the textbox and clicks another link (not the submit button) how do I display the 'Are you sure you want to navigate away from this page' popup message?
I have researched this on the net and found a few javascript examples. Is this the only way you can do this? If not, what is the best way to do it?
This is one of the multiple ways to achieve the same thing
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
got it from here open js
Only the unload() event will work on JS. You can't manage it on the server.
Check out the answer to this other question on SO, it is very similar to your question
How to show the "Are you sure you want to navigate away from this page?" when changes committed?
Simple solution
window.onbeforeunload = confirmExit;
function confirmExit() {
return "Are you sure you want to leave this page?";
}
4guysFromRolla.com - Prompting a user to Save when Leaving a Page
You cannot use the onbeforeunload window method as it gets triggered by multiple ways like back and forth browser navigation links, refreshing the page, closing of the page, clicking on the links.
What i feel you have to bind the link tag for which you want display the navigation away message and then use the function for the status message display
window.addEvent('domready',function(){
$$('a').addEvent('click', function(e) {
//leaving(); function u wrote for displaying message
});
});
function leaving(e) {
if(!e)
e = window.event;
// return code for the displaying message
}
If you want to do this in a way that guarantees it will work on almost all browsers, use the JQuery library. The following describes the unload event.
http://www.w3schools.com/jquery/event_unload.asp
It's exactly for purposes like yours.
Just to elaborate a little, you would have to download the jquery js library and reference it in your project/page, but you'll probably want to do that eventually anyway.
If you want to control this from the server side, you can dynamically emit the jquery call in the OnPreRender.
Look into Jquery's .beforeunload property. Here is an example:
$(window).bind('beforeunload', function(){ return 'Click OK to exit'; });
Please note, beforeunload canot prevent a page from unloading or redirect it to another page for obvious reasons; it would be too easy to abuse. Also if you just want to run a function before unloading, try the following:
$(window).unload(function(){ alert('Bye.'); });
Finally, don't forget to referrence jQuery in your head tag by using:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
The above gets you the latest version from the internet and saves you the trouble to download it, and of course you can do so optionally, but I am just trying to get your thing to work asap.
Oh, I also found an example for you. Click here to see a page that calls a function before it closes. Hope this helps bud.
I was able to get this to work with Andrei G's answer. I would add on that to get it to work in Chrome, add this to the end of his goodbye function:
return "";
* IE6 restrict button click to once. *
I have a button, which should be clicked once, and when clicked at first time I need to run few back-end logics(operations) for example save some data in DB, send Email, do some logging, and after the success of these operations I need to redirect to the other page.
But I am using
btnMakeFO.Visible = false ;
after the button's click event, the user is still able to click it more than twice.
I have also used the:
btnMakeFO.Enabled = false ;
but it is not working too.
I have also used the following at the button's(btnMakeFO_Click) click Event Handler :
btnMakeFO.Attributes.Add("onclick", "this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(btnMakeFO, "").ToString());
I have searched a lot regarding this issue, but I am unable to find the solution customized to my problem.
NOTE: I am developing on the Windows 7 x-64 bit machine and IE8, here the button is clicked at maximum twice. In FireFox8 it is clicked only once.
But at the Production Environment there is Windows 2003 Server, Internet Explorer 6, at this server the button is able to be clicked even more than twice i.e. the btnMakeFO button can be clicked about 10 to 15 times consecutively. (The Internet Explorer 6 at Production Server cannot be upgraded because few older applications will not run correctly in the newer versions of Internet Explorer.)
I need to fix this issue at earliest by tomorrow. Kindly help me in this regards at your earliest.
BTW I have used the following (which I found from Code Project), it is working greatly and I am happy with this solution.
<asp:Button OnClick="btnMakeFO_Click" OnClientClick="clickOnce(this, 'ABC...')">
<script type="text/javascript">
function clickOnce(btn, msg)
{
// Test if we are doing a validation
if (typeof(Page_ClientValidate) == 'function')
{
// if we are doing a validation, return if it's false
if (Page_ClientValidate() == false)
{
return false;
}
}
// Ensure that the button is not of type "submit"
if (btn.getAttribute('type') == 'button')
{
// The msg attibute is absolutely optional
// msg will be the text of the button while it's disabled
if (!msg || (msg='undefined'))
{
msg = 'Saving.......';
}
btn.value = msg;
// The magic :D
btn.disabled = true;
}
return true;
}
</script>
The javascript approach should work.
You are injecting the code from the server-side, which can be challenging. You should still be able to see the results when you run the app and View Source in the browser. You should see the javascript in the tag, like this:
<input type="submit" value="Submit" onclick="this.disabled=true" />
For ASP.Net, you might also try the OnClientClick event, which you can add directly to the HTML, instead of injecting it from your page code-behind.
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");
});