Allowing POST method to an HTML page in ASP.NET MVC - asp.net-mvc

Allowing POST method to an HTML page in ASP.NET MVC
I am using ASP.NET with MVC 5.2 and I am integrating RoxyFileManager to my CKEditor.
The integration was fine, the problem is when I try to upload some file to my web server, I got this error:
NetworkError: 405 Method Not Allowed - http://localhost:35418/FileManager/index.html?...
The RoxyFileManager uses the POST method to upload the file and my webserver does not accept it. I can't figure out how can I fix it.
If I put manually an image to my directory I can see it in the file manager, also I can create and exclude folders there.
To clarify my question: I want to know how can I make my webserver accept the POST method to a HTML page, just it. All the relevant information are above. I have a HTML page and want to make it accept POST.
#UPDATE:
I've figured out the problem is a browser issue.
In Google Chrome everything works fine;
In Firefox I get the error above;
In IE things seens to work fine, but it have cache problems (I can upload and edit previously sent files, but I can't see the changes neither the recent file uploads until cache expires);
I'll work on these problems and post the answer here, if successful.

To solve the IE bug it's simple but it's hard-work: You need to add in every ajax call of RoxyFileMan the line cache: false. You need to do it in every .js file on the RoxyFileMan folder.
Example:
$.ajax({
url: d, dataType: "json", async: true, success: function (h) {
for (i = 0; i < h.length; i++) { e.push(new File(h[i].p, h[i].s, h[i].t, h[i].w, h[i].h)) }
g.FilesLoaded(e)
},
error: function (h) { alert(t("E_LoadingAjax") + " " + d) },
cache: false
})
With this, all the ajax made by Roxy will have no cache, solving the IE issue.
To solve the Firefox bug I've changed this in the main.min.js:
BEFORE:
document.forms.addfile.action = RoxyFilemanConf.UPLOAD
AFTER:
$('form[name="addfile"]').attr('action', RoxyFilemanConf.UPLOAD);
I've found this solution here.
And now my file manager is working on all modern browsers.

Related

File download feature in grails application

I am looking to create a file on the fly and offer a download link to the user in a GRAILS application.
I followed the approach from here. I have no errors however it doesn't seem to work. Here's my controller code.
`render (file: pptFile, fileName:'someppt.pptx', contentType: 'application/octet-stream')
Client side code makes an AJAX call to retrieve the file from server. It does not cause the server to force downloading of the file on the client (browser). Here's the client side code.
$.ajax({
type : 'POST',
url : '<<URL>>',
success: function(result) {
var uri = 'data:application/octet-stream;charset=UTF-8,' +
encodeURIComponent(result);
window.open(uri, 'somePPT.pptx');
},
failure: function(){
alert ('failure')
}
});
Perhaps something akin to this (paraphrased, but used for downloading a json file):
def someControllerMethod() {
def dlContent = someService.marshalJson()
def contentType = "application/octet-stream"
def filename = "someFilename.json"
response.setHeader("Content-Disposition", "attachment;filename=${filename}")
render(contentType: contentType, text: dlContent as JSON)
}
okay. So I finally got this to work. As proposed by #railsdog and many others (This problem has been discussed on other threads in stackoverflow but the specific case I had was slightly different from those) I ended up writing to response directly from server and took out the AJAX call. The only reason I was doing an AJAX call was because I did not want to submit the current page that had the "generate file" functionality (There are many data elements on the page and I did not want to re-do the entire page just for downloading the file). So I ended up using an anchor tag with target as "_blank". Here's the code snippet
<a href="myControllerMethodToGenerateFileAndWriteToHTTPResponseDirectlyAsSuggestedByOthersInThisPost"
target="_blank"/>
This actually opened a new page and did the submission to initiate the download. Problem solved. It's working fine in CHROME. :) Thanks guys!
I like the solution using the render method from #railsdog !
A slightly other approach which I used so far was:
def controllerMethod() {
...
File file = sepaXmlService.createTransfersFile(...)
response.setContentType("application/xml")
response.setHeader("Content-disposition", "attachment;filename=${file.getName()}")
OutputStream out = response.getOutputStream()
out.write(file.bytes)
out.close()
file.delete()
return
...
}
In the view I use the following statement in the form:
<g:actionSubmit action="controllerMethod" class="btn" value="Get XML!" /></td>
I think it should also be possible to use a
<g:link controller="foobar" action="controllerMethod" class="btn">GetXML</g:link>

AJAX Call returning 404(Local) in IIS 7.5 but same works in other IIS

Am having the AJAX calls to my controller in my MVC Application
Controller/FunctionName
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '/Controller/FunctionName',
.
.
.
)};
Am using MVC 4 and making use of JQUERY Ajax function as shown in the above code. It works totally fine when i run from Visual studio.
I depolyed this to the server machine and as expected it works fine. No issues found in AJAX calls.
Now am trying to deploy this in my local machine IIS which is same as my server version (IIS 7.5) but am getting 404 for all the ajax calls in firebug.
I verified the build and even i pointed to my web folder and am still looking for what went wrong !!
It works in other IIS so It wont be a URL resolving issue is my gues. Am i missing any settings or Any timely idea to fix this would be great.
Thanks
That's normal. You have hardcoded the url to your controller action:
url: '/Controller/FunctionName',
If you deploy your application in a virtual directory in IIS the correct url should be:
url: '/YourAppName/Controller/FunctionName',
That's the reason why you should absolutely never hardcode urls in an ASP.NET MVC application but ALWAYS use url helpers to generate it:
url: '#Url.Action("FunctionName", "Controller")',
and if this AJAX call is in a separate javascript file where you cannot use server side helpers, then you could read this url from some DOM element that you are AJAXifying.
For example let's suppose that you had an anchor:
#Html.ActionLink("click me", "FunctionName", "Controller", null, new { id = "myLink" })
that you AJAXify:
$('#myLink').click(function() {
$.ajax({
url: this.href,
contentType: 'application/json; charset=utf-8',
type: 'GET',
.
.
.
)};
return false;
});
Notice how we are reading the url from the DOM element which was generated by a helper.
Conclusion and 2 rules of thumb:
NEVER EVER hardcode an url in an ASP.NET MVC application
ABSOLUTELY ALWAYS use url helpers when dealing with urls in an ASP.NET MVC application
Just a complement of Darin's answer that if "the AJAX call is in a separate javascript file where you cannot use server side helpers", use a hidden field to store the url endpoint in the view:
#Html.Hidden("URLEndpointName", Url.Action("FunctionName", "Controller"))
and read that hidden field in your js:
url: $("#URLEndpointName").val(),
You can use double dot in the url:
$.ajax({
url: '../ControllerName/ActionName',
.......
});
What I'd found on my setup of IIS7.5 is that the 'Handler Mapping' has a resource named 'OPTIONSVerbHandler' is not set in the right order hence return back as Unknown.
This work for me where my localhost ajax was calling my network server, which has a different name, that it shouldn't give me a CORS issue, but it did and this was my solution.
Open IIS and click on your server name on the left pane. On the right pane double-click 'Handler Mappings' in the middle pane. On the right pane, select 'View Ordered List'. From there find 'OPTIONSVerbHandler' and 'svc-ISAPI-4.0_32bit', move 'OPTIONSVerbHandler' up until it is above 'svc-ISAPI-4.0_32bit'.
Make sure your 'handler' inside your ajax call does not have 'Access-Control-Allow-Origin' in it.

CouchDB Update XML Attachement

Ive read at least 5 articles on this but I can't seem to get it. I have an xml file that is already in memory in the browser and I am attempting to update a document from my db, for which I already have the doc id. What is the best way of doing this? Is there support for this built into jquery.couch.js, because I can't seem to find any.
Ive attached some code with hard coded values for the sake of my sanity:
var xmlTemp = this.fullscoreApp.MusicXML.document;
$.couch.db("mydb").saveDoc({
"_id": "67e98623efefe16d27e2177b44000aee",
"_rev": "4-830aad7c3dc9e1d5004439ed1c9196d3",
"type":"score",
"_attachments":xmlTemp
}, {
success: function() {
console.log("PLZ");
}
});
I get a DOM 18 error...but I'm using a public server. Thoughts?
What protocol are you using to open your JavaScript file? Are you running it via a webserver (such as http://localhost) or just opening the file (which will show as file:// in the browser)?
If the latter, the browser will report DOM 18, because file:// suffers various restrictions not present for pages served by a webserver. More info from this question.

ajax request in rails 2 not working

function ajaxRequest(){
$.ajax({
type: 'GET',
url: 'client/orders/send_mail_to_notaries',
data: { subject: "hi" }
});
return false;
}
It doesn't pass any params in controller.Can any one trigger this out?
Following the question that you have asked today morning page.replace_html method in rails 2 i guess you are using prototype.
Can you check if jQuery is included? Unless jQuery is included this ajax request will not work.
I just tried the method you're using and it worked for me. Perhaps there's a problem with the router/controller?
When debugging ajax it's very handy to use the Chrome developer toolbar. Bring it up, run the javascript and see what happens.
To see the response from the server you can then flip to the Network tab to see what the response is.

Jquery mobile page navigation corrupts base url and causes ajax on main page to fail

My main page is here:
http://www.mydomain.com/main/main.php
My login page is here:
http://www.mydomain.com/main/pages/login.php
Main.php uses ajax to fetch data in response to a tap event. This works fine until I navigate to my login page and then back to my main page. After going to the login page and back, the relative paths get messed up such that the ajax looks for server file in the wrong place.
here is the ajax:
1. function get_more_data() {
2. more_data_index += 15;
3. var formData = "index=" + more_data_index;
4. $.ajax({
5. type: "POST",
6. url: "genxml.php", // file located here: http://www.mydomain.com/main/genxml.php
7. cache: false,
8. data: formData,
9. dataType: "xml",
10. success: showFiles3,
11. error: onErrorMoreData
12. });
13. }
After I navigate back to main.php from login.php the ajax tries posting to the wrong location:
http://www.mydomain.com/main/pages/genxml.php
(genxml.php is not in the "pages" subdirectory; it's in the main directory.)
I tried updating the ajax to use an absolute path:
url: "http://www.mydomain.com/main/genxml.php"
This made the post successful, but my data parsing failed because relatives paths are used in the main file for things like images. So instead of getting images from here: http://www.mydomain.com/main/ the script was trying to get images from here: http://www.mydomain.com/main/pages/
I've found a few posts with people having similar issues, but I've not come across a solution. I've also tried reading the jquerymobile docs and it's very possible that the jquery developers attempt to cover this issue here, but I admit I don't completely understand everything on this page:
http://jquerymobile.com/demos/1.0b3/#/demos/1.0b3/docs/pages/page-navmodel.html
If anyone can help I would really appreciate it. Thanks.
P.S. This issue happens on Android and Google Chrome, but not in Firefox.
I have created a working example of what you're trying to do. You should be able to look at this and see what I've done. Be sure to checkout the master.js. I think that the key to making it work in your situation is to nest the ajax calls within the "pageshow" event to be sure that your baseURL has been updated. You can download the example at http://www.roughlybrilliant.com/stackoverflow/7372909.7z
View the example in action as it pulls in weather.xml with relative URLs.
$("div").live("pageshow", function(){
var $page = $(this);
get_more_data();
});
Why don't you use one of this:
use "../main.php" when redirecting back from login page, or
remember UrlRefer from Headers when you entering login.php and use that to redirect back to any previous page with 301

Resources