Diffence between usage of Ajax Update Panel and Jquery:ajax() method - asp.net

I am little confused about Update Panel usage and usage of Jquery:Ajax() method.
Do both of them are used for Partial Post backs..
Which is the best approach to fallow?
Please help me on this..

An update panel performs a full re-render of the page, takes the section matching the panel and sends it back to the client. The browser then replaces the contents of the update panel with the new html.
jQuery's AJAX method allows you to make any request to any page and handle the response data any way you choose. This might include reading a JSON response from a web service, getting html or anything else you wish. Effectively AJAX gives you a mechanism to emulate the user browsing to a given url with GET or POST data and manipulate the results in any way you desire.
It's worth noting that the update panel is built on top of AJAX (technically Javascript's XMLHttpRequest) object.
There are also some gotchas with update panel, eg if you have a Captcha that is outside the panel; When the panel is updated, the captcha visible to the user doesn't change. The server generates a new page, including a new captcha. When the user submits the form, their verification code is for an old captcha.
In short, you have more control with AJAX and learning how to use it will be beneficial but depending on your use case, an update panel may do what you need for less effort.

Related

Submit form to both code behind and third party url?

I have a legacy app that I need to change to accommodate a new payment processor.
The app is Asp.Net.
Without reconstructing the app (not in the budget) I need to take the final form and save information from it in the code behind, like it currently does, then I need to submit that same form to a third party url. Ideally as one button push to the end user.
I'm drawing a complete blank on a way to do this. Any suggestions?
Forgot to mention that JQuery and javascript are both valid tools for a solution.
You could create a javascript function that's bound to the form submit button's click event, or the form's submit event. The function will need to prevent the default form submission from firing. Use jQuery to serialize the form data, and create a synchronous AJAX request to submit the data to the third party. After the ajax submission has completed, you can trigger the form submission to the code-behind. If the ajax fails to submit properly, you can optionally abort the form submission to the code-behind.
You may need to account for XSS security, so look into cross-origin resource sharing and the Access-Control-Allow-Origin header.
Another option would be to have the code-behind behave as an http client and submit the form data to the third party.
so currently it's saving the results via code? Well, you could hack it by putting some javascript on the page that read's the forms values and posts them (eg with jquery), before doing you actual asp post.
edit (something like this might help (in some cases):
//change the action of the form (you could just change in code or this
$('#myform').attr('action','http://newpaymentproc.com/me/');
//override the default submit
$('#myformsubmitbutton').click(function(){
//extract the form data somehow (depends on form)
var formObj;
$.each($('#myform').find('input').serializeArray(), function(i, field) {
formObj[field.name] = field.value;
});
//post to old place
$.post('/old_current.asp', formObj).then(
//after posting to old place and getting response...
//submit form to new payment processor
$('#myform').submit()
);
// Cancel the actual form submit click to give time for post
return false;
});
Another way would be to have the legacy code (after submission) spit out a form with the data in it and some javascript to trigger submit on page load.
After the original process has completed, just take the submitted form data and push it to whichever URL you're working with. It requires minimal modification on the original app.
I have no code to go on, so I have no code to give. Hope that helps!

Avoid hidden field in the web forms

I have a web page and a modal dialog page. On clicking the save button in the show modal dialog. closes the window and returns a value. Now when the
control reaches the JavaScript function of the parent window . I wnt to perform some database operation on the basis of this returned ID.
I am using the following approach to utilize this returned value.
Keeping it in the hidden field and populating the returned value in hidden control.
keeping a hidden button in the parent window, performing the click event when control comes back to JavaScript function of the parent page. Thus in the server side button handler get the value from hidden field and perform database operation on the basis of returned value.
Is this approach fine. Or I can get rid of hidden field
That's not terribly bad provided the ID returned is not sensitive information that someone can use to modify a record that doesn't belong to him. One can perfectly manipulate this ID on the client side for any other ID and have your logic update a different record from what you intended.
If all you are doing is calling a server side method passing this ID; why don't you do the whole update from the pop-window itself (at that point you already know the ID)?
If the parent window (page) is meant to be updated; you can just perform a normal refresh of the page (ie. use window.location to redirect the user to the same page so he can see the update or use Response.Redirect to the same page.)
What you're probably looking for is called AJAX. With AJAX you can communicate with your web server from within your JavaScript code directly. No HTML form posts are required then. You might want to look at frameworks like JQuery. These have easy implementations (cross browser wrappers) to send HTTP requests via AJAX.
Note: I just noticed, you are using ASP.NET. Take a look at ASP.Net AJAX Page Methods.

aspx ashx mash-up

I'm retro-fitting a .aspx page with AJAX functionality (using VB, not C#). The codebehind populates the page with data pulled from a web-service. The page has two panels that are populted (with different data, of course) in this way. On a full page refresh, one or both panels might need to be populated. But populating Panel 2 can take a long time, and I need to be able to update panel 1 without refreshing Panel 2. Hence the need for AJAX (right?)
The solution I've come up with still has the old .aspx page with .aspx.vb codebehind, but introduces a Generic Handler (.ashx) page into the mix. Those first two components do the work on the user's first visit or on a full page refresh, but when AJAX is invoked, the request is handled by the .ashx page.
First question: Is this sound architecture? I haven't found a situation online quite like mine. Originally, I wanted to make the .aspx page into the AJAX handler by having the codebehind implement IHttpRequest, and then providing "ProcessRequest" and "IsReusable" methods, but I found I couldn't separate a regular visit to the page from an AJAX request, so my AJAX handlers took over even on the first visit to the page. Second question: Am I right to think that this approach (making the .aspx page do double-duty as the AJAX handler) will never work? Is it impossible to tell whether we're getting a full-page request or a partial-page (AJAX) request?
If the architecture is good, then I need to dynamically generate a lot of HTML in the .ashx file, right? If that is right, should I send HTML back to the client, or should I encode it in some way? I've heard of JSON encryption, but haven't figured out how to use it yet. So, Third question: Is "context.Response.Write" the only pipeline for sending data back to the client? And, if so, should I send back HTML or some kind of JSON-encoded objects?
Thanks in advance.
It sounds as if the page requires some AJAX functionality added to the UI.
Suggest using an UpdatePanel for each web form element that needs to have AJAXy refresh
functionality. That'll save you from having to refactor a bunch of code, and introduce a whole lot of HTML creation on your .ashx.
It'll be more maintainable over the long run, and require a shorter development cycle.
As pointed out by others, UpdatePanel would be a easier way - but you need to use multiple update panels with UpdateMode property set as conditional. Then you can trigger the update-panel refresh using any button on the page (see AsyncPostBackTrigger) or even using java-script (see this & this). On the server side, you may decide what has triggered the partial post-back and act accordingly by bypassing certain code if not needed.
You can also go with your approach - trick here is to capture the page output using HttpServerUtility.Execute in your ashx and write it back into the response (see this article where this trick has been used to capture user control output). Only limitation with this approach is that you can only simulate GET requests to your page and so you may have to change your page to accept parameters via query string. Personally, I will suggest that you create a user control that accept parameters via method/properties and will generate necessary output and then use the control on your page and in ashx (by dynmaically loading it in a temperory page - see this article).
EDIT: I am using jquery to illustrate how to do it from grid-row-view.
$(document).ready(function() {
$("tr.ajax-grid-row").click(function() {
$("#hidden-field-id").val($(this).find(".row-id").val()); // fill hidden filed
$("#hidden-button-id").click(); // simulate button click
});
});
You can place above script in the head element in markup - it is assuming that you have decorated each grid-row-view with css class "ajax-grid-row" and each row will have hidden field decorated with css class "row-id" to store row identifier or the value that you want to pass to server for that row. You can also use cell (but then you need to use innerHTML to get the value per row). "hidden-field-id" and "hidden-button-id" are client ids for hidden field and submit button - you should use Control.ClientID to get actual control ids if those are server controls.
JSON is not for that purpose, it is to pass objects serialized with a nice light weight notation, is you need to stream dinamically generated html using ashx, response.Write is what you have. You may want to take a look at MVC
Or you could use jquery if it's just html, the simpliest would be the load function, or you can look into Ajax with jquery. Since the ashx can be served as any resource it can be used in the load function.
I agree with #p.campbell and #R0MANARMY here. UpdatePanel could be the easiest approach here.
But then like me, if you don't want to go the UpdatePanel route, I don't see anything wrong with your approach. However, generating the html dynamically (entirely) at the back end is not a route I'll personally prefer (for the maintainence reasons). I'd rather prefer implementing a solution that will keep the design separate from the data.

Is javascript reliable for preventing actions on the front end such as form submission?

I have a webservice that I need called, the result of which determines whether or not the user is allowed to submit the form.
Since this call is from javascript and not from code behind is it not reliable? Is there any way the user can get around the check -- by either going in with firebug and enabling the submit button, somehow making the method give a different result than was actually returned by the webservice, any other ways of being able to get around it?
Basically is there any way to call a webservice from javascript and have it's result determine whether or not a form can be submitted, and actually prevent the user from submitting the form at all? -- whether or not they have firebug, etc...
No, not possible.
Just to name a few possible reasons:
what if javascript is disabled?
what if the user submits the raw POST (using libcurl, for example)?
what if the browser, that the user is using interprets javascript in a way, different from your expectations (think, portable devices)?
Javascript validation is there for your users' convenience only and should never ever be used as a means of providing security.
You can never prevent the user from making an HTTP request that mimics submission of the form. While disabling the form via Javascript prevents submission for 95% of the users who both have Javascript enabled and don't want to circumvent your access control, anyone who understands HTTP can make the call and you are correct in showing that anyone with Firebug can do it in a matter of seconds.
Javascript isn't reliable for preventing anything. It shouldn't be seen as a security-wall, as it's too easily disassembled with things like firebug, iedevelopertoolbar, and many other browser toys.
Even if you could prevent them from submitting your form on your page, nothing stops them from creating a brand new form, on their own page, and point it toward the action of your form. Thus they're removing themselves from your "secure" environment, and instead chosing to play in their own.
Your suspicion is correct; the user can easily get around any possible Javascript validation.
You will need to use server-side code.
No, it is not reliable. Try disabling Javascript in your browser to see for yourself how easily you can get around it.
The user could simply disable javascript in their browser, or use something like NoScript. The best you could do is to try setting the form action itself in the return from the Ajax request, that way the form, as loaded, won't submit (except to itself). This will probably stop casual users but would be no impediment to a slightly more determined (or just bored and tech savvy) user. You will need to check on the server side whatever you do.
In general, no. You can make the form hard to submit without going through Javascript. Make the submit button not an actual submit button (<input type="submit">), but a pushbutton (<input type="button">) that submits the form in its onClick handler.
As everyone else said, no you can't do it. The only real solution is to have the web service return some dynamic value which the Javascript inserts in a hidden form input. Then whatever server-side code processes the form submission should reject the request if that value is not present.

can i repost or carry POST data (if so, can i do it with redirects?)

I want to redirect the user to another page to fill out a captcha but i would like to keep the post data, and if the captcha pass to send it 'back' and complete the previous page action.
When/if the user succeeds i like to add an captchaPass=true and would like access the post data and continue processing. Right now i am using redirects but ATM i am not required to use it.
Is it possible to carry the post data? keep in mind i may the user access multiple pages so separating data and not having a mixup is necessary.
One idea is to get and save all posted data [1] on the captcha page, and then recreate a middle white page with this form data and automatically make a new post to the previous page.
Can this work with out any issues with hash checks and security ?
Is there a better idea with out this white redirect page ?
[1] One other issue here, how to send this posted data with the redirect ? and not change the url - or make it too big to accept it. Keep in mine that a server transfer may not good idea because is complicate the thinks on captach post back.
Update 1
The basic idea here is how some one capture the full post back of a page, show a different one page and then send the post back data to the original first one.
The reason is to stop a bad user, or an attacker bot program that try to bring down the pages/server by making many post back from different pages in short time. All that happens with out javascript, and most attackers use custom made programs that just make post of data to all page together try to bring down the system.
For example, if a page have a search box, is very easy for most of the the site to bring them down by start making hundred of random search with wildcard (called and Dos Attacks using SQL wildcards) and make the sql server and the computer spend his time and cpu to search and search thinks. So to prevent an attack like this you need to recognize multiple post backs from the same computer, and then the next step is to redirect him to a captcha page to block him out in case that is a computer program.
Other example, many page have email submit, very easy you can submit hundred times the email of his and full his mail box in no time with hundred of emails, or on a store to place all items on the cart again and again and full the database with stuff like that.
So ajax and javascript is not working in this case, and we need a way to redirect him after the post back to a page that can check if is a real user or an attacker and stop him - but if is a real user must return back to his normal action.
Update 2
This all must be done in a general way, eg on BasePage, or on Global.asax or somewhere that is independed from the content of any page. Because we try to prevent a DoS attack, or multiple submit anywhere on any random place of any random page.
Yes I know how you can place a captcha on the contact page, but this is not what this question was first asked for - this questions asked how can carry post data to one different page, keep them there and then resend them back to the original one.
The obvious solution is to read all post back, and save them on the form, and then read them back and make on fly a form only with that data and make the post back. Here I am asking if there are any other better than this solution.
Other Applications
There is also the case that a user is inside a page that request authentication, but the authentication ticket has expired, and the user make post back. In this case we need to keep somewhere all the posted back data, to proceed with the login page, and resend them back to the first page that request the authentication.
Sure, just write the form data out to the captcha page in hidden elements with the additional captcha fields added to the form. Have your submit action post the whole thing back to the original. Using ASP.NET it's probably easier to have the captcha written to the same page with the form fields hidden, but you can do cross-page postbacks as I've described above.
Cross Page Posting might help you.
Why not implement the CAPTCHA with AJAX? Load the captcha object and form with Javascript in a div perhaps displayed lightbox style, accept the user input and post it to your server for validation, hence continue with the users post request or keep them there until they get it right (or cancel).
A more specific situation example:
Give the form submittal button an onClientClick value of some Javascript function. This function decides if this particular form needs a CAPTCHA. If it does it loads an interface for taking the CAPTCHA (which you'd need to do with some server-side code) and inserts the CAPTCHA's input element to the form that the user clicked to submit.
Once the user has entered the CAPTCHA input and clicks some button whose click event is bound to return to your first JS function, the Javascript intercepts this action and posts the full form, all the data from the original form and the CAPTCHA for validation. Your server script can now process all this at once!
This is the best solution I can think of that works similar to how you've asked, but I can't imagine why you want to perform the CAPTCHA on a different page.
Server.Transfer with MultiViews, Panels like control is fine with you? In this way, no need to bother about the Data Maintenance and Postbacks. You can do the validations in javascript.
You can keep both functionality in the same page to avoid moving data from one page to another page/Bring the data back to original page. You can utilize Session for this intermediate operation. Set it back to associated controls across Postback. You can create a class, Instantiate it and Initialize the control values in this class object. Save class object in Session. On Postback, You can reassign the values to the associated controls. This will definitely keep the things simple and without much complexity.
Doubts ?

Resources