I've been struggling for the whole weekend with unwanted postbacks.
The popup I'm working on has a button that basicaly fires a few stored procedures and then closes the pop up window.
What I wanted to achieve is to have the same result when people hit the X closing buton on the top right.
So, X button = myCloseButton.
For that I've done this.
AJAX.
$(window).unload(function(){
var dataToSend = { MethodName: 'UpdateR' };
var options =
{
data: dataToSend,
dataType: 'JSON',
type: 'POST',
};
$.ajax(options);
});
.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ #region Ajax methods
if (Request.Form["MethodName"] == "UpdateR")
{
UpdateRegister();
return;
}
#endregion
}
}
And then UpdateRegister() executes the code that I want to execute once people leave the page.
So, the problem comes when people hit another(whatever) control inside the pop up page. The page enters the (!IsPostBack) and the AJAX method. That's understandable since I'm saying on .unload do this and that. (I've tried $(window).bind('beforeunload', function() and it's not working for the desired purpose)
Any idea on "How can I tell the page to difference when it's a closing event like X button or my control, and any other control on the page?" would be much appreciated.
Thanks.
EDIT. It's not something about serializing the form and comparing before leaving. No, it's about logins and stuff, so even if people open the pop up and close it immediately I need to get that.
Why not you create WebMethod and directly call instead of calling via Page_Load() page event.
[WebMethod]
public static string UpdateRegister()
{
// your update register script here
}
Sample call from jquery, you can call this ajax when someone click on load or unload button.
You can call ajax script when button with id "button1" clicked e.g
$(function(){
$('#button1').click(function() {
// close window
window.close();
// call ajax script to perform server side script
$.ajax({
type: "POST",
url: "Sample.aspx/UpdateRegister",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
In case someone gets here with an error something like this:
Answer:
All that was begin a mess in my webform was a button (an asp one). It was postbacking, so I disabled the postback via javascript and that was it. I'm now able to move forward.
Related
I have a button and have postback function as btnSubmit.Click in the code behind.
<asp:Button runat="server" ID="btnSubmit" Text="Submit" UseSubmitBehavior="true" OnClientClick="ajaxCall(); return false;" />
Now, i want to do a pre-post action, which will call an ajax to do some calculation, and have a confirmation box to allow user to click "Ok" - resume original button's function do to the postback, or "Cancel" - simply just cancel the postback.
<script type="text/javascript" language="javascript">
function ajaxCall() {
$.ajax({
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
url: "ODS.aspx/ClientCall",
success: function (msg) {
alert(msg);
}, error: function (data) {
alert(data);
}
});
}
</script>
I kept getting either only fire the confirmation box, but the "OK" won't work, or the postback will over the ajax. I know there must be a smart way to do this, to interrupt the normal button submit postback behavior, but don't want to introduce more controls, something like hiddenbutton or so, feels like very hacky way. Any thoughts?
I dont know weather it will solve your problem or not but you can use ajaxStart and ajaxStop method and in those methods you can write your logic of confirmation..
Another option from ajaxStart and ajaxStop and jquery .after().
Is if you were to use a ASP:LinkButton you can store the href property in a variable, remove it when the client clicks, when you need it to execute just do eval([HREFVariable]).
This is from memory but I am going to look it up in a minute:
$('a.whatever').on("click", function(){
e.preventDefault();//stop the post back
var defaultAction = $(this).prop("href");
//do stuff
//you are ready now
eval(defaultAction);
});
This works because ASP.Net does postbacks in the href like javascript:__doPostBack(...);
So this just calls the function you were going to do.
Edit 2 Since you want to stay with the asp:button
Something like this should work
$('a.whatever').on("click", function(){
e.preventDefault();//stop the post back
var id = $(this).prop('id');
//do stuff
//you are ready now
__doPostBack(id, '');
});
I am guessing on this part though. This should fire the correct post back, but I have not tested it.
I having a problem that seems i can'f find a solution to which is the following:
I have a master page that have a menu, each link in the menu is a LinkButton.
I am required that whenever a user click on a certain link to show a login popup so i used Ajax ModalPopupExtender and i successfully showed the popup.
Now i want to validate the user which means that i will need to input username and password and press login but since i am in a popup it will close because of postback so i suppressed the postback and now i have to do the checking from the Client side so i need to call a server method from a javascript function, i tried using the PageMethods but i keep getting PageMethdos not defined, then i read that it won't work inside master pages or user controls.
Any solution to my problem ?
PageMethods are to be used in aspx pages , not in MasterPage Methods. The only workaround is to create a seperate .asmx WebService and add your Logic in a static function . To Do so , right click on your solution on VS and click on Add New Item, Select WebService.asmx.
in the code behind of the WebService write a static webMethod
[WebMethod]// press alt+shift+f10 after selecting the WebMethod wording to include the library
public static bool CheckLogin (string username, string password){
//Type your method here
return result;//Result should be Boolean
}
Now on your masterPage.master on client side script click event of the link, Post an Ajax Request to the webservice
$.ajax({
type: "POST",
url: "YourWebServiceName.asmx/CheckLogin",
data: '{"Username":"' + $('#username').val() + '","password":"' +
$('#password').val() + '"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(message) {
alert(message);//will alert 'true'
//DO what you want to do on client side
},
error: function() {
alert(message);//will alert 'false'
//DO what you want to do on client side
}
});
Please let me know if you need any further clarification
Have a nice day :)
One solution is to create a base class for all your pages and put the page method there. For example:
public class CustomBasePage : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static bool ValidateUser(...)
{
bool isValid = false;
...
return isValid;
}
}
Now all you content page should deliver from CustomBasePage instead of Page:
//public partial class Index : System.Web.UI.Page
public partial class Index : CustomBasePage
{
...
}
This way you write the method only once and it is accessible always, so you can depend on it in your master page.
Did you try adding the <base target="_self"> tag in the head of the page. It will make sure that the postback happens in the original page.
I am working in ASP.NET MVC 3 and using Telerik. I have an empty telerik window. My goal is to only ask server for content when the user clicks a button, however I have no idea how this could be done. I imagine that to accomplish this I would need to store a reference to the telerik window in question. But how do i do this? plz help. This is how far I have got:
#{
Html.Telerik().Window()
.Name("ImportDialog")
.ClientEvents(events => events.OnOpen("DialogOpen"))
.Visible(false)
.Title("Import users")
.Draggable(false)
.Resizable(resizing => resizing.Enabled(false))
.Modal(true)
.Width(400)
.Height(400)
.Render();
}
I do want do do somethin in DialogOpen function, or alternatevly replace that client side function with a server side funciton....
You should use the client API of the Telerik Window and more specifically the ajaxRequest method.
So for example when the button is clicked you should get the client object and call the ajaxRequest method which will make the Window retrieve its content from that MVC action method.
e.g.
function DialogOpen(){
var myWin= $('#ImportDialog').data('tWindow');
myWin.ajaxRequest("Controller/Action", { name: "John",location:"Boston"});
}
I found one type of answer, however i am not sure yet if it is the best.
In the javascript function DialogOpen I send an ajax request to an url(also known as an Action of a Controller in MVC), the I put the result in the content of the dialog window, like so:
function DialogOpen ()
{
$.ajax({
type: "POST",
url: "Controller/Action",
data: "name=John&location=Boston",
success: function (htmlContent)
{
$('#ImportDialogContent').html(htmlContent);
},
error: function ()
{
$('#ImportDialogContent').html("<p>Could not import user data at this time</p>");
}
});
}
P.S.: I gave an ID to content area of telerik Window(ImportDialogContent)!
I will start by telling I'm not an ASC/C# developer, this is for a homework. (i hope somebody will understand what i want :D, because i dont know exactly the terms)
I have Friends.aspx and Friends.aspx.cs
In Friends.aspx i have something like
<%# Reference Control="~/FriendBox.ascx" %>
<div class="controlcontainer clearfix friendlist_containeritems" id="divFriends" runat="server"> </div>
In Friends.aspx.cs i have this to populate divFriends:
foreach (FBUser user in list){
Control control = LoadControl("FriendBox.ascx");
FriendBox myControl = (FriendBox)control;
myControl.user = user;
divFriends.Controls.Add(myControl);
}
In my page a have a form, and divFriends is inside the form. I have a button in this form. If i just press the button, my page gets submitted and i can retrieve values from selected checkboxes. (Every control contains a checkbox)
Everithing worked fine until i tried to submit the page via Ajax (JQuery).
My problem is that even the checkboxes are on page (i can se them, select them), when i do an ajax submit i cannot access values from checkboxes.
This is the code i use to retrieve values from checkboxes:
foreach(Control ctrl in divFriends.Controls) {
var friendBox = ctrl as FriendBox;
//i can get here
if (friendBox != null)
{ //i never get here - because friendBox is allways null }
}
How can i make the content from divFriends accesible when i submit my form with Jquery?
Thanks in advance.
Edit: here is the javascript i use
$(document).ready(function () {
$('.big').click(function () {
//.big is my button
$('.big').attr('disabled', true);
var form_form = $(document).find('form');
$.ajax({
type: 'POST',
url: form_form.attr('action'),
data: form_form.serialize(),
dataType: 'json',
success: function (data) {
console.log('success');
},
complete: function (XMLHttpRequest, textStatus) {
$('.big').attr('disabled', false);
}
});
return false;
});
});
The javascript is working because i can submit data, and i can receive data back (json), when i look at the data submited i dont have the checkboxes from divFriends.
The problem appears to be asp.net state managment issue. You are only adding FriendBox one time (I'm assuming, probably with an if not page.ispostback sort of thign), and not on each page hit. Since FriendBox is added dynamically it's not surviving a postback and thus it does not exist when you try to read it.
You should add FriendBox each time the page loads, on Init before viewstate is loaded. Adding the controls during on init will allow Viewstate to track the values and will probably fix the issue.
I have code in code behind portion of my aspx page. On a button click a function gets called so that a clickonce application loads. Originally I was doing all of this in javascript. The js set the window.location to the url of my clickonce application, and close through a timeout. This worked fine until I installed the application on another server. IE does not allow the clickonce application to get loaded through client side script. I am now forced to do a redirect to the url of the clickonce application. The problem that I'm encountering now is not having access to be able to close the window where the redirect was initiated from. The redirect fires first before any js could run. I basically need a way to slow down the redirect so that i can run my js.
You could redirect to a page that will have the JavaScript you had before - to close the window and redirect to the clickonce application. You could pass the URL of the application to this page in the query string. The page could be plain html.
you could do something like this. I am using jquery but you dont have too..
webmethod = GetUrlToApplication, is basically returning path.
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetUrlToApplication",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: ajaxSucceededFn,
error: errorFn
});
});
function errorFn ()
{
alert('Error:-Unable to launch Application.');
}
function ajaxSucceededFn (result)
{
window.location = result;
setTimeout(function() { window.open('', '_self', ''); window.close(); }, 1000);
}
</script>