How to open file using Ajax in MVC - javascript

I have an hyperlink of the file name and want to download the file retrieved from database. I can download the file, but the form is posted during this process. Instead of this, I want the form is not posted with the help of ajax, but my code hits error in Ajax call. Is there a smart way to achieve this?
View:
<a onclick="downloadFile(#Model.ID);" target="blank">#Model.FileName</a>
<script>
function downloadFile(id) {
$.ajax({
url: '#Url.Action("Download", "Controller")',
type: "POST",
data: JSON.stringify({ 'id': id }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("error occurs on the database level!");
}
},
error : function () {
alert("an error has occured!!!");
}
});
}
</script>
Controller:
public FileContentResult Download(int id)
{
var dataContext = repository.Attachments.FirstOrDefault(p => p.ID == id);
if (dataContext != null)
{
return File(dataContext.FileData, dataContext.FileMimeType);
}
else
{
return null;
}
}

why not just change your link to
<a href="#Url.Action("Download", "Controller", new { id = Model.ID })" >#Model.FileName</a>

The easiest way to download a file is to link it directly like calling the action: "/FileController/Download?Id=2"
The problem is that if you get an error, it will redirect you to a blank page...
To resolve this i created this function:
function DownloadFile(id, Type) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
if (Type == undefined || Type == "")
Type = null;
iframe.src = "/File/Download?ID=" + id;
}
This function creates an hidden iframe pointing to the file path (action). If it gives an error, it will not blow up your page.

Related

Pass parameters to Common.js from Aspx in .Net

I have a web application with Common.js and it has the following function which is calling when this button btnBookingStatus was clicked.
$(document).on('click', '#btnBookingStatus', function () {
var req = new Object();
req.strMinNo = $(parent.document).find('#hdnFMinNo').val();
req.strSeqNo = $(parent.document).find("#hdnPSeqNo").val();
req.strUserId = $(parent.document).find("#hdnUserId").val();
if (req.strMinNo == undefined || req.strMinNo == '') {
req.strMinNo = $(parent.document).find('#hdnMinNo').val();
}
if (req.strSeqNo == undefined || req.strSeqNo == '') {
req.strSeqNo = $(parent.document).find('#hdnFinSeqNo').val();
}
if (req.strUserId == undefined || req.strUserId == '') {
req.strUserId = $(parent.document).find('#hdnCurrentUserId').val();
}
$.ajax({
type: "POST",
data: JSON.stringify(req),
url: "../Common/LibUiUtilities.aspx/fnCreamsBookingStatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != null) {
var retData = JSON.parse(data.d);
if (retData.oRetunStatus == 'P' || retData.oRetunStatus == 'null') {
alert("Creams Booking still in progress...");
}
else {
$(parent.document).find('#drpBookingStatus').removeAttr('disabled');
$(parent.document).find('#drpBookingStatus').val(retData.oRetunStatus);
$(parent.document).find('#drpBookingStatus').attr('readonly', true);
alert("Creams Booking Success");
}
if (retData.oReturnMsg != undefined && retData.oReturnMsg != 'null') {
$(parent.document).find('#lblBkWarningMsg').text(retData.oReturnMsg);
} else {
$(parent.document).find('#lblBkWarningMsg').empty();
}
}
}
});
});
There are 5 client windows with the same btnBookingStatus button with the same functionality, which needs to be called the above-mentioned JS function. But the hidden field names which pass the parameters are different.
For eg:-
Form1.aspx --> hdnFMinNo, hdnFSeqNo
Form2.aspx --> hdnPMinNo, hdnPSeqNo
Form3.aspx --> hdnMinNo, hdnSeqNo
These element Ids can not be changed
I wanted to pass the parameters (MIN_NO and SEQ_NO) from ASPX to the Common.js without accessing the parent window's elements.
Please help me out with this.

json login session error

i used a json login data file to login with php. i used javascript to search any user in the json data file and show me page or redirect to login page.
$(document).ready(function () {
$('#login').click(function () {
var email = $('#email').val();
var pass = $('#pass').val();
var error = true;
$.ajax({
type: "POST",
url: "login.json",
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
if (email == value.email && pass == value.pass) {
error = false;
}
});
if (error == false) {
document.location = "index.php?email=" + email;
} else {
$('#email').val('');
$('#pass').val('');
alert('please check your email or password!');
}
}
});
return false;
});
});
this works fine. but i used to login with my url and it also access any email to my index.php file. how to make to this correct.
i type like this on url and it also shows me index file.
http://json.test/index.php?email=test123#gmail.com
i want to restrict this method and only login with json file data. can anyone know how to make php session with this JavaScript code.

Ajax submit an ajax loaded form

I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.

How to catch session timeout in ajax call?

Please note that I had already tried to apply the solution on Handling session timeout in ajax calls but did not worked for me.
In an ASP.NET MVC5 project, I open pages by rendering partialview via AJAX as shown below:
function renderPartial(e, controller, action) {
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
var message = errorThrown;
if (jqXHR.responseJSON != null) {
message = jqXHR.responseJSON.message;
}
},
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
//Load partialview
$("#div-page-content").html(data);
}
});
};
On the other hand, when session timeout and call this method by a hyperlink, there is an empty white page on the partialview field where partialview page should be rendered. So, is it possible:
1) to display a partialview at this field?
2) to redirect user Login page?
Note: I would also be happy if you suggest a smart way to Handle Session Expire in ASP.NET MVC. Thanks in advance...

How to hide current page

I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}

Categories