asp.net How to resume button's postback after ajax completion? - c#

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.

Related

How to post back the html page source of the current page that is loaded(no refresh)?

The subject says it all but i'll further explain. If i am on a page that has a button on it, how can i wire up the button to capture the page source and send it back to the controller for storing it? I can store it as byte array or any file type. I can't find any solutions for posting back the page source of the current page. All the examples i have found use something like WebClient which you supply a url for it to load up and then capture the html.
if you have a button with id="btn" here is the sample:
<script>
$('#btn').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: $('html').html(),
url: 'exmaplesite.com/postaction',
success: function () {
alert('success');
}
});
})
</script>

Writing to SQL Server Compact database from jquery mouseup event

I'm working on an asp.net c# empty web forms project. I have a SQL Server Compact database with a single table that I want to use to store information about an elements (x,y) coordinates.
The database should be updated with the new coordinates for a particular panel when the mouseup event is triggered on that panel (a div essentially). The solution doesn't need to be ajax, submitting the page will be ok.
The problem is that there is no mouseup type of event for an <asp:Panel> element and on the other side I'm not sure how I would trigger something server-side from jQuery. Getting the coordinates using jQuery is easy enough, but what would I do from there?
Are hidden inputs ok for this? Give me your best solution - I don't need to see code, just give me a better idea of what i should be doing.
Thanks!
First check what exactly asp:Panel is getting rendered in browser by firebug, suppose it renders as div then you can use jquery's .mouseup() function and bind this event to what ever element that panel is rendered. Suppose if that asp:panel is rendered as div then look this below code for sample.
<div id="asp_panel">
Click here
</div>
$('#asp_panel').mouseup(function() {
$.ajax({
url: "HelloWorld.asmx/Hello",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}", // if your method takes any parameter pass it in here in json format.
dataType: "JSON"
success: function(msg) {
alert(msg);
}
});
});

AJAX / Postback Issue

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.

Reset onclick so value isn't used by ajax script

I have a beginform that automatically sends EVERYTHING to the controller via a ajax script. The problem is I have one button in the form that should only send its value once per click. I cant seem to distinguish it between the rest of the automatic data.
GOAL: Once the button is clicked once, i want value 10 (from button) to stop posting to the controller.
AJAX FUNCTION (SUBMITS ALL DATA TO CONTROLLER)
function toconroller() {
$.ajax({
type: 'POST',
url: this.action,
data: $('form').serialize(),
success: function (result) {
$('#box').html(result.info);
}
});
}
BUTTON FUNCTION
Function submitonce() {
//I want to only submit value of button once.
}
BEGINFORM WITH BUTTON
#using (Html.BeginForm())
{
<input id="data" onkeyup="tocontroller();">
<input type="submit" name="clicked" id="clicked" value="10" onclick="submitonce();" />
}
You could remove the value attribute of the submit button when clicked:
function submitonce() {
$('#clicked').removeAttr('value');
}
or do it unobtrusively without using the onclick attribute but subscribing to the .click() handler using jQuery:
$(function() {
$('#clicked').click(function() {
$(this).removeAttr('value');
});
});
or instead of removing the value attribute of the button you might want to set it to empty or something else:
$('#clicked').val('');
And since this is a submit button you might want to cancel its default action of submitting the form by returning false from its click handler (my second unobtrusive jQuery example).

Asp.net retrieve content from a Control

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.

Categories