I getting this error "Request URL Too Long" when i tried to download the file. The url shows the data that i want to download but it doesn't download.
How can i solve Request URL Too Long error when downloading
my code
Javascript
<script>
function DownloadIndexController(possID) {
$.ajax({
url: '#Url.Action("DownloadIndex", "Poss")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: { possID: possID },
type: "GET",
success: function (returnValue) {
window.location = '/DownloadIndex/Poss' + returnValue;
}
})
}
</script>
Controller
[HttpGet]
public virtual ActionResult DownloadIndex(int possID)
{
try
{
possFilename = possFilename.Replace(",", ",");
string fullPath = Filelocation + possFilename;
return File(fullPath, System.Net.Mime.MediaTypeNames.Application.Octet, possFilename);
}
catch (Exception ex)
{
throw ex;
}
You cannot use ajax to download a file in that way.
What you need to do is to generate a normal download link for every item in your grid, like:
#Html.ActionLink("Download", "DownloadIndex", "Home", new { possID = "123" }, null)
Where Home is the name of your controller, and you have to dynamically add the possID for every item instead of the hard coded 123 in my example.
In your code, you download the file using ajax, and then you redirect to an url containing the full file just after '/DownloadIndex/Poss'
You probably just want to redirect to the file, without using Ajax at all :
<script>
function DownloadIndexController(possID) {
window.location = '/DownloadIndex/Poss?possID=' + possID;
}
</script>
Related
I need a script that passes a json string to a function in the controller and process the response pdf document to be seen as downloads to the user.
I return a pdf document of FileResult data type in c# as the response for an ajax call which passes a JSON string to the function.
I need this pdf document to be seen as downloads to the user. How can I perform this? I tried to write code in the success of ajax but the control goes to error and by debugging I found it to be a parse error.
Ajax code is like
function Download(){
$.ajax({
method: "POST",
url: "{url to the action}",
data: {
//Send json data that you want
}
success:function (e){
alert('success');
},
error:function(){
alert("error");
}
})
}
C# code is like:
public FileResult getPDF(string statementHTML)
{
//code to convert to pdf file
File file = //pdf document with MIME 'apllication/pdf'
return file;
}
When the above code executes the error alert is invoked but this c# function returns a pdf document but seems like ajax don't accept it.
You don't really need to ajax to make this download call, you can just do this.
function DownloadFile(){
//do some calculation
window.location="{url to the action}?argument1=value1&argument2=value2....."
}
However if you have to do it via ajax, you can get download.js and do this.
function DownloadFileUsingAjax(){
$.ajax({
url: "{url to the action}",
data: {
//Send json data that you want
}
})
.done(function(data){
//download function is from download.js
download(data, fileName, fileMimeType);
});
}
For another way, you could try mock the button click event to download the file like
Client Side.
#section Scripts{
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '/Home/GetPDF',
method: 'get',
contentType:'application/json',
xhrFields: {
responseType: 'blob'
},
success: function (data, status, response) {
var filename = "";
var disposition = response.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
let a = document.createElement('a');
a.href = window.URL.createObjectURL(data);
a.download = filename;
document.body.append(a);
a.click();
window.URL.revokeObjectURL(url);
}
});
});
</script>
}
Controller
public FileResult GetPDF(string statementHTML)
{
var fileByte = System.IO.File.ReadAllBytes(#"xxx\Test.pdf");
return File(fileByte, "apllication/pdf", "Test.pdf");
}
I cannot get DotNetNuke to execute the backend code from my JQuery Ajax function.
I have the following JQuery code on my View.ascx file
I did try to change the URL to View.ascx/DeleteReviewData but no luck.
function deleteReview(ReviewID){
var ReviewIDToDelete = ReviewID;
$.ajax({
type: "POST",
contentType: "application/json",
url: "https://dnndev.me/Product-View/DeleteReviewData",
data: "{'deleteReviewID': '"+ ReviewIDToDelete +"'}",
datatype: "json",
success: function (data) {
alert("Delete successfull");
},
error: function (error) {
alert(error);
}
});
}
This is my back-end code which doesn't get executed on the View.ascx.cs file:
[System.Web.Services.WebMethod]
public static void DeleteReviewData(int deleteReviewID)
{
try
{
//Deletes a review from the database
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()))
{
connection.Open();
using (SqlCommand command = new SqlCommand($"delete from ProductReviews where ReviewID = {deleteReviewID}"))
{
command.Connection = connection;
command.ExecuteNonQuery();
}
connection.Close();
}
}
catch(Exception ex)
{
throw;
}
}
If I should use MapHttpRoute. Does someone have an example, please?
I looked at the following post, but I am not sure about using RouteConfig.cs and extra headers and etc: https://www.dnnsoftware.com/answers/execute-an-action-by-calling-an-ajax-post
I currently get no Console errors. It goes to the success section.
When I hover over Type, ContentType or any one of those while debugging it says not defined. See example below. The site is using JQuery 01.09.01
2nd image
UPDATE
I have changed the URL which now gives me a 404 error: url: $.fn.GetBaseURL() + 'DesktopModules/ProductDetailedView/DeleteReviewData'
I also tried this URL path with adding API API/DeleteReviewData , but I get a [object Object] error as it shows a 404 error in the console.
This is an example:
$.ajax({
data: { "Id": IdToDelete },
type: "POST",
dataType: "json",
url: "/DesktopModules/{API-ProjectName}/API/Main/DeleteExpenseByID"
}).complete(function () {
//...
});
Api method:
[HttpPost]
[DnnAuthorize]
public void DeleteExpenseByID(int Id)
{
//...
}
You need to send a number so you dont need the "'" surrounding ReviewIDToDelete var.
Also check DeleteReviewData for a [POST] attribute, it seems to be a [GET] call.
I am realy struggling with this and would apprecate any advice.
I have this field
<input id="scanInput" type="text" placeholder="SCAN" class="form-control" />
For which I would like to make an ajax call when the field changes, so I tried
<script>
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=GetPartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
</script>
Where my PageModel has this method
[HttpPost]
public IActionResult GetPartDetails()
{
return new JsonResult("hello");
}
and the url for the page in question is /packing/package/{id}
Now when I change the input value, I see ye on the console, and I can see that the network called http://localhost:7601/Packing/Package/40?handler=GetPartDetails (the correct URL I think?) with status code 200
But My breakpoint in GetPartDetails never hits, and I don't see yay? in the console.
I also see this message from the fail handler:
Request Failed: parsererror, SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data
But I'm not even passing any JSON data... why must it do this
I also tried this way :
$.ajax({
type: "POST",
url: "?handler=GetPartDetails",
contentType : "application/json",
dataType: "json"
})
but I get
XML Parsing Error: no element found
Location: http://localhost:7601/Packing/Package/40?handler=GetPartDetails
Line Number 1, Column 1:
I also tried
$.ajax({
url: '/?handler=Filter',
data: {
data: "input"
},
error: function (ts) { alert(ts.responseText) }
})
.done(function (result) {
console.log('done')
}).fail(function (data) {
console.log('fail')
});
with Action
public JsonResult OnGetFilter(string data)
{
return new JsonResult("result");
}
but here I see the result text in the console but my breakpoint never hits the action and there are no network errors..............
What am I doing wrong?
Excuse me for posting this answer, I'd rather do this in the comment section, but I don't have the privilege yet.
Shouldn't your PageModel look like this ?
[HttpPost]
public IActionResult GetPartDetails() {
return new JsonResult {
Text = "text", Value = "value"
};
}
Somehow I found a setup that works but I have no idea why..
PageModel
[HttpGet]
public IActionResult OnGetPart(string input)
{
var bellNumber = input.Split('_')[1];
var partDetail = _context.Parts.FirstOrDefault(p => p.BellNumber == bellNumber);
return new JsonResult(partDetail);
}
Razor Page
$.ajax({
type: 'GET',
url: "/Packing/Package/" + #Model.Package.Id,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
input: barcode,
handler: 'Part'
},
success: function (datas) {
console.log('success');
$('#partDescription').html(datas.description);
}
});
For this issue, it is related with the Razor page handler. For default handler routing.
Handler methods for HTTP verbs ("unnamed" handler methods) follow a
convention: On[Async] (appending Async is optional but
recommended for async methods).
For your original post, to make it work with steps below:
Change GetPartDetails to OnGetPartDetails which handler is PartDetails and http verb is Get.
Remove [HttpPost] which already define the Get verb by OnGet.
Client Request
#section Scripts{
<script type="text/javascript">
$(document).ready(function(){
$("#scanInput").change(function () {
console.log('ye');
$.getJSON("?handler=PartDetails", function (data) {
//Do something with the data.
console.log('yay?');
}).fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
});
});
</script>
}
You also could custom above rule by follow the above link to replace the default page app model provider
I have a base image, and I use C# Graphics library to add data to it, and then return the image converted to byte array.
I have a controller:
public ActionResult DisplayDR(int drNum)
{
ER dr = DataUtility.getDR(drNum, errors);
return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}
That works fine with,
<img id="drImage" src="#Url.Action("DisplayDR")" width="1110" height="484" alt="qr code" />
I need to be able to dynamically update the image and attempted with ajax with no luck.
Using:
function getNewDRImage(instance) {
var drNum = $(instance).data('val');
var src = '#Url.Action("DisplayDR", "Home", new { area = "Part" })';
$.ajax({
type: "GET",
url: src,
data: { drNum : drNum },
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (err) {
var msg = "Client side error, " + err;
throwClientSideErrorMsg(msg)
},
success: function (data) {
$('#drImage').attr("src", data.image);
}
});
}
and returning JSON like so,
public JsonResult DisplayDMR(int drNum)
{
ER dr = DataUtility.getDR(drNum, errors);
return
Json(new { image = File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png") }, JsonRequestBehavior.AllowGet);
}
Gives me this error:
System.Web.HttpException (0x80004005): The controller for path '/[object Object]' was not found or does not implement IController.
What am I not doing correctly?
update, viewing the source after the ajax call I see why the error occurs, as this is what the response is:
<img id="dmrImage" src="[object Object]" alt="qr code" height="484" width="1110">
So I guess I am confused on what to do with the JSON data to update the image.
With your ajax code you're trying to load actual bytes of your image and assign that to the src attribute. That's not what the attribute expects.
All you need is to just assign a new image url as a string. The browser then will automatically fetch actual bytes and show the new image for you.
If you want to use the same url for the updated image you need to make sure the browser won't use your old cached image. Take a look at this answer for how to do this.
To add Cache-Control: header to your File() response use Response.AddHeader() method:
public ActionResult DisplayDR(int drNum)
{
Response.AddHeader("Cache-Control", "no-store");
ER dr = DataUtility.getDR(drNum, errors);
return File(DrawDRUtility.getDRimageAsByteArray(dr), "image/png");
}
I have a submit button on a form, when it's pressed the form is submitted and an Excel file is created on the server harddrive (C:/ExcelFiles).
After this has been done (after de form is submitted) I want to download this file using Ajax.
This is what I've done but it's not working:
$(document).on('click', '#saveButton', function () {
$('#saveMessage').empty();
$('#saveMessage').append("<p>Your file has been stored in C:\\ExcelFiles</p>");
var data = $('#fileName').val();
alert(data);
$.ajax({
type: 'POST',
url: '/Calculation/Download',
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (returnValue) {
window.location = '/Calculation/Download?fileName=' + returnValue;
}
});
});
And my controller action look like this:
[HttpGet]
public virtual ActionResult Download(string fileName)
{
string fullPath = Path.Combine(Server.MapPath("~/ExcelFiles"), fileName);
return File(fullPath, "application/vnd.ms-excel", fileName);
}
Right now nothing happens. What am I doing wrong?
You cannot download files from the server by .ajax (due to security reasons).
You can however point the browser to that location and download the file.
The solution should be something like this:
$(document).on('click', '#saveButton', function () {
$('#saveMessage').empty();
$('#saveMessage').append("<p>Your file has been stored in C:\\ExcelFiles</p>");
var data = $('#fileName').val();
window.location = '/Calculation/Download?fileName=' + data ;
});