Implementing Anti forgery for Telerik upload control - asp.net-mvc-3

I have come across implementing Anti forgery token for a POST method when its an ajax call,the couple of things I do here are
[1]Include[ValidateAntiForgeryToken] attribute for my POST controller method.
[2]Change $.ajax call to $.ajaxAntiForgery in my js.
Similarly I have a telerik upload control where I trigger the controller method from cshtml(instead of an ajax call)- cshtml code snippet below
#{ var upload = #Html.Telerik().Upload()
.Name("attachments")
.Multiple(true)
.Async(async => async.Save("MyMethodName", "MyConrollerName")
In this case, how do I implement antiforgery? What changes I need to do in cshtml, controller?
Thanks,
Adarsh

Hello if you use the Kendo Upload wrapper for MVC the antiforgery will be send automatically to the server.
Since you are using the old extensions you might need to use the OnUpload event to manually find that value and send it to the server.
e.g.
function onMyUpload(e){
e.data = { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() };
}

Related

Upload pdf using ajax and servlet [duplicate]

Can I send a file as multipart by XMLHttpRequest to a servlet?
I am making a form and submitting it as multipart, but somehow I am not getting a response for successfully uploading it. I do not want the page to be refreshed, so it has to take place by Ajax.
That's only possible with the XHR FormData API (previously known being part of as "XHR2" or "XHR Level 2", currently known as "XHR Advanced Features").
Given this HTML,
<input type="file" id="myFileField" name="myFile" />
you can upload it as below:
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "myServletUrl");
xhr.send(formData);
XHR will take care about proper headers and request body encoding and the file will in this example be available on the server side as form-data part with the name myFile.
You need to keep in mind that FormData API is not supported in older browsers. At caniuse.com you can see that it's currently implemented in Chrome 7+, Firefox 3.5+, Safari 5+, Internet Explorer 10+ and Opera 12+.
In case you're using jQuery, then you might be tempted to use its $.val() function as below:
formData.append("myFile", $("#myFileField").val());
But this is incorrect as it doesn't return the whole File object, but merely the file name as String which is utterly useless as it doesn't contain the file contents.
If you don't want to use document.getElementById() for some reason, then use one of the following instead:
formData.append("myFile", $("#myFileField").prop("files")[0]);
formData.append("myFile", $("#myFileField")[0].files[0]);
An alternative is to use the jQuery Form plugin. Your entire form, when written and functioning properly without any line of JavaScript code, will then instantly be ajaxified with just the following line:
$("#formId").ajaxForm(function(response) {
// Handle Ajax response here.
});
It also supports file uploads as well by a hidden iframe trick. See also this jQuery Form documentation for an in-depth explanation. You may only need to change the servlet code to be able to intercept on both normal (synchronous) and Ajax (asynchronous) requests. See also this answer for a concrete example: Simple calculator with JSP/Servlet and Ajax
Either way, the uploaded file should then be available in the doPost() method of a #MultipartConfig servlet as follows:
Part myFile = request.getPart("myFile");
Or if you're still on Servlet 2.5 or older, use Apache Commons FileUpload the usual way. See also this answer for a concrete example: How can I upload files to a server using JSP/Servlet?
It's not possible to send multipart/form-data with XMLHttpRequest (though it is possible in modern browsers, with XHR2. See BalusC's answer).
A common way to achieve what you want is to use a regular form, but in an iframe instead. This way, only the iframe is refreshed on upload.

Extend/Override jquery.ajax.done function to detect .net logon screen

I'm using forms authentication on an asp.net MVC application and I'm using jquery and ajax to create a rich user interface. Some users tend to leave the page open for hours and their login session is expiring as expected. If the user click a link or reloads the page the login screen is returned as expected. If they click a button or trigger an ajax call the ajax call is returning the login html instead of the expected html or JASON result. Resulting in a mangled page with half a login screen.
As I've already coded a lot of ajax calls I thought I could extend or override the default .done event to add a check for the login screen before continuing with whatever event I've programmed.
For example i have this function :
function CallAjax() {
$.ajax({type: "GET", url: "foo" })
.done(function (data) { $('#result').val(data); });
}
is it possible to override the default implementation of .done so do a check without rewriting this function? My check would probably to see if the result is a html response if so search for "login" to see if its the login page.
I would recommend you to extend the ASP.NET Forms Authentication module as Phil Haack explained in this blog post so that it no longer redirects to the login page when requested with AJAX but returns a 401 HTTP status code instead. Then you could simply use the .fail callback and intercept the 401 status code. The .done handler will not be invoked in this case.
I tried Darin's suggestion but after hours of trying I just couldn't get it to work in my set up. However I stumbled across this rather simpler solution which worked for me first time:
just add this to the global.asax
protected void Application_EndRequest()
{
var context = new HttpContextWrapper(this.Context);
if (FormsAuthentication.IsEnabled &&
context.Response.StatusCode == 302 &&
context.Request.IsAjaxRequest())
{
context.Response.Clear();
context.Response.StatusCode = 401;
}
}
}
Taken from http://jvance.com/blog/2012/09/21/FixFormsAuthentication302.xhtml

Cross domain javascript ajax request - status 200 OK but no response

Here is my situation:
Im creating a widget that site admins can embed in their site and the data are stored in my server. So the script basically has to make an ajax request to a php file in my server to update the database. Right? Right :)
The ajax request works excellent when i run it in my local server but it does not work when the php file is on my ONLINE server.
This is the code im using:
var url = "http://www.mydomain.net/ajax_php.php";
var params = "com=ins&id=1&mail=mymail#site.net";
http.async = true;
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//do my things here
alert( http.responseText );
}
}
http.send(params);
In firebug it shows: http://www.mydomain.net/ajax_php.php 200 OK X 600ms.
When i check the ajax responnseText I always get a Status:0
Now my question is: "Can i do cross-domain ajax requests by default? Might this be a cross-domain ajax problem? Since it works when the requested file resides in my local server but DOESN'T work when the requested file is in another server, im thinking ajax requests to another remote server might be denied? Can you help me clear on this?
Thanks..
Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:
function receiveData(data) {
// ...
}
And then your server wraps JSON data in a function call, like this:
receiveData({"the": "data"});
And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.
Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.
You're going to need to have your response sent back to your client via a JSONP call.
What you'll need to do is to have your request for data wrapped in a script tag. Your server will respond with your data wrapped in a function call. By downloading the script as an external resource, your browser will execute the script (just like adding a reference to an external JS file like jQuery) and pass the data to a known JS method. Your JS method will then take the data and do whatever you need to do with it.
Lots of steps involved. Using a library like jQuery provides a lot of support for this.
Hope this helps.

ASP.NET MVC 3 - enabled unobtrusive javascript, ajaxComplete fires once and never again

Before unobtrusive javascript, I handled ajax complete events with the following register:
Sys.Net.WebRequestManager.add_completedRequest(myHandler);
This event handler will fire every time an ajax request is complete. I also have an ajaxComplete event bind in $(document).ready(), to handle ajax calls exclusively through jQuery:
$.ajaxComplete(function (e, xhr, settings) {
myHandler(xhr)
});
Which also works great. But I get a different behavior when I enabled unobstrusive javascript in ASP.NET MVC 3. It fires the first time when the first ajax call is complete, but on subsequent ajax requests, ajaxComplete event never fires again.
Now, I know about that you need to call $.validate.unobtrusive.parse() to rebuild the validation after the elements in the form updated via partial postback. Is there something similar that I need to do to make sure that ajaxComplete can fire again on subsequent requests? I cannot find the documentation on this.
FYI: I have included all the jquery*.js libs to support unobtrusive javascript. I also have the MicrosoftMvc*.js libs included to support legacy code in the project. I was hoping to convert everything over until I ran into this problem.
You need to actually attach ajaxComplete to an element I thought?
$('.info').ajaxComplete(function() {
var info = $(this);
info.html('Success!');
});
You should only need to attach ajaxComplete to an element once in its lifetime.

Favourite AJAX library for classic ASP?

Just wondering if there are any good server-side libraries for AJAX (prefer JSON rather then XML but anything is good) for classic ASP (VBScript)...
Rather not reinvent the wheel if it's already working and debugged.
Cheers,
Gaspard
EDIT: Server-side ASP VBScript... I have already seen many javascript client side libraries.
Try jQuery. It's amazing!
I am using ajaxed which seems to be one of the few still maintained ajax libraries for classic asp out there. Its working very well for me. It's using prototypejs as its js lib. JSON is fully supported.
You don't really need a server-side library. Accepting POSTs and GETs from AJAX is the same as accepting them the "old fashioned" way. What is key here are good design patterns.
I commonly use a single function to dispatch my simple Ajax calls in Javascript (I use Prototype):
function fetch(elelment,cmd,id) {
//general purpose AJAX function
$(elelment).innerHTML='Loading...<br /><img src="/images/spinner.gif">'
now = new Date()
url = 'http://..../Ajax.asp?CMD='+cmd+'&ID='+pid+'&now='+now
new Ajax.Updater(elelment, url, { method: 'get' });
}
Then on the server side I typically use a select case, break it down by command, fetch the record by the passed ID, and spit out an HTML fragment. I usually build a function to spit out any JSON I need separately.

Resources