launch an excel file from a Controller using JavaScript - c#

What do I need to do to open an excel file via controller action using javascript?
I tried the this way but it does not open the file.
JavaScript Function:
function ExcelExport() {
var link = '/Report/ExcelExportData';
$.ajax({
type: 'POST',
url: link,
success: function (result) {
},
error: function (result) {
}
});
};
Controller Action:
public ActionResult ExcelExportData()
{
return File("~/Reports/ExcelFile.xlsm", Server.UrlEncode("~/Reports/ExcelFile.xlsm"));
}

Actually, you can't open files directly from ajax callback responses. You could try two different approaches:
Use an anchor for opening the file and get rid of the ajax request. Something like <a href="/Report/ExcelExportData"> will do.
Call window.open(link) inside your success callback. The only advantage of this approach is that it allows you to handle unexpected errors (file not found or something like that). It will perform another roundtrip to the server, though.

Related

Ajax not recognized in JQuery file

I uploaded to GitHub days ago an MVC project, I've downloaded it again, and want to set some new functions using JQuery Ajax, but now when I'm trying to do something like this:
$("#btnTrigger").click(function () {
$.ajax({
type: "get",
url: "/Orders/MyJson/"
}).success(function (result) {
alert(result.testing)
})
});
An exception is thrown: Object doesn't support property or method 'success'.
I think that something is wrong with JQuery, when I'm going to write $.ajax inside a function the keyword ajax is not displayed, instead Intellisense shows other keywords like attr etc. Normally the keyword ajax is displayed from Intellisense.
I've been trying uninstaling and installing JQuery again and nothing happened, I've check the BundleConfig class to check if the JQuery files are added and they are there, I've installed unobtrusive ajax and have added it to BundleConfig class too and still the problem continues... What it could be??
Try it like this, putting the success inside ajax definition
$("#btnTrigger").click(function () {
$.ajax({
type: "get",
url: "/Orders/MyJson/",
success: {
function (result) {
alert(result.testing);
}
}})})

JSON data POST to Web API works in Fiddler but "Not Found" error from JQuery AJAX

my stuff works fine with Fiddler and I get desired result. But when i do it on web page thru JQuery AJAx, it says "Not Found". I am struggling since sometime but couldn't get around.
My Controller method is like this
[Route("AddDonors/")]
[HttpPost]
public dynamic addDonors(localDonor localDonor)
{
return localDonor;
}
This is how i am calling from web page
var userInput = { 'FullName': 'Lakshman', 'Mobile': '9924210053' };
$.ajax({
type: "POST",
url: "/AddDonors",
data: userInput,
error: function (result) {
alert(result);
},
datatype: "json"
});
this is the model class
public class localDonor
{
public String FullName { get; set; }
public String Mobile { get; set; }
}
API registering and other settings are just fine since this works in fiddler.
Please help. Thanks.
I strongly suspect that the url in your AJAX request is to blame (404 - Not Found) the request can't be routed to a controller for processing.
Without knowing what your full controller looks like and if you have a RoutePrefixAttribute on this specific controller I can't say what the url should be.
I would suggest you monitor network traffic in your browser developer tools (press F12) and compare the request url for your failing POST request to those of your successful requests in Fiddler
If your webpage is created in ASP.Net MVC as part of the same web project you may want to generate the url server side in future see Construct url in view for Web Api with attribute routing. The #Url helper is only available within your .cshtml files though so you will not be able you shift your JavaScript code to a separate .js file.
i was able to solve the issue by changing the url to url: "AddDonors",
Try to put [WebMethod] attribute.
[Route("AddDonors/")]
[HttpPost]
[WebMethod]
public dynamic addDonors(localDonor localDonor)
{
return localDonor;
}
Hope this works!
Try this for your POST data
var userInput = JSON.stringify({ 'FullName': 'Lakshman', 'Mobile': '9924210053' }),
I had the same error.
As you are using ASP.NET, try making all AJAX calls using the #Url.Action helper.I don't know why, but in some situations in ASP.NET passing the URL as a String doesn't work.And try passing your data like the code belowYour modified code should look something like this:
$.ajax({
type: "POST",
url: "#Url.Action("AddDonors", "ControllerName")",
data: { localDonor: userInput },
error: function (result) {
alert(result);
},
datatype: "json"
});

How to return two pdf files in one action result?

I need to return two PDF files on postback in MVC, but the action result is returning only one file. Is there any other way is there to return more than one file in an action result?
return File(stream, "application/pdf", Summary.pdf);
Like this I need to return more than one file.
An ActionResult returned from an action in a controller always represents one thing, and since there is no concept of multi-file references in HTML, you have to make two separate steps, or merge the existing action in one step.
So you have three options:
Create two hyperlinks, with two separate actions to call. Generate a report in either of them. Return a FileResult like you do now.
Put your files in a zip file, and send that one over. The nice thing is that you only need one action. The bad thing is that users have to unzip the file before they can view the report. To make this work, you first have to generate both documents, use a library to zip the files, and then return that using a FileResult or a stream.
Merge the two reports into one. If this is feasible depends if the documents are that related they can be considered one. You can use a library to merge them together and send back the merged report.
My bet would be on option 1 unless you have very good reasons not to do so.
if you use ajax , you can create file links and send back link with json and then open links in javascripts.
server side:
...
retrun Json(new {.link1 = "stackoverflow.com" ,
.link2 = "stackexchange.com"})
and client side :
$.ajax({
url: "#Url.Action("ActionName" , "ControllerName")",
type: "post",
datatype: "json",
data: data,
success: function(sucess) {
if(success.link1 != undefined)
{
var win = window.open(d.link1 , '_blank');
var win1 = window.open(d.link2 , '_blank');
if (win==undefined) {
//Broswer has blocked it
alert(' Activate your browser popup');
}
}
},
error: function () { console.log("error"); }
});

How the form data is converted to a model in C# .Net MVC3 , entity framework?

I have a code like below
View:
$("form").live('submit', function () {
var formData = $(this).toObject();
$.ajax({
url: "../Home/Index",
type: "POST",
dataType: "json",
data: formData,
success: function (data) {<<Some handling>>
}
Controller:
public JsonResult Index(Task task)
{
//operations on the task object like getting data from task and setting to it.
}
Task is a model here.
Here when the form is submitted, the form object is directly sent to the controller and the controller is receiving it as a model.
How this conversion takes place? I have added a file component to the form now
<input type="file" name = "file" id="file"/>
and added the file attribute to model Task.
public HttpPostedFileBase file{ get; set; }
But I am getting null for the file in the controller. But all other values are coming well.
Please help me out. Please let me know if you need any additional info to understand my question correctly.
Normally it's the model binder that is responsible for converting the request values into a model.
But in your case you seem to be attempting to send a file using AJAX. This is not supported. The reason for that is because jQuery's ajax method doesn't support that. You could use HTML5 File API if the client browser supports it because the XHR2 object allows you to asynchronously upload files to the server. Here's an example:
$(document).on('submit', 'form', function () {
var xhr = new XMLHttpRequest();
xhr.open(this.method, this.action);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText); // handle response.
}
};
xhr.send(new FormData(this));
return false;
}
Also notice that I have used the .on() method to subscribe to the submit event instead of .live() which is obsolete and has been removed in jQuery 1.9.
If on the other hand you need to support legacy browsers you could use a plugin such as Fine Uploader or jQuery form to achieve this task. What those plugins do is detect the capabilities of your browser and if it supports XHR2 it will use it, and if it doesn't it will use a different technique (such as hidden iframes, flash, ...).
You can not file upload using jquery ajax post directly. You should you some plug-in for this.
May be you can use this plug-in
This question will show you a start point for using this plug in.
Also, I learned it from #DarinDimitov suggestions, too :)

Use jquery/ajax to call a c# (or any other .net) function in another project within the same solution

Does anyone know if it's possible to use jquery/ajax to call a c# (or any other .net) function in another project within the same solution?
Let's say that the solution's name is ExampleSolution , the name of the project from which I call the target function is Project.Source and the name of the target project is Project.Target,
and the name of the target function is TargetFunction().
I've tried following in an .js file in the Project.Source:
$.ajax({
url: '/ExampleSolution/Project.Target/TargetFunction',
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
Then I've modified the url-line in several ways but never succeed.
Do you have any advice?
Thank you all for your fast answers.
I found a solution for the problem and I'd like to share it just in case anybody faces the same problem in the future.
In the .js file before I call the $.ajax function I create a variable with help of window.location which points to the url to the targetfunction of the running target-project and use the variable in the ajax-function. So you don't point to another project. You point to url of running project.
Just as easy as it sounds.
Below follows the solution:
var url = window.location = 'http://localhost:13105/TargetFunction';
$.ajax({
url: url,
type: 'get',
success: function (data) {
$(document.body).append(data);
}
});
});
You can only call functions in the Code Behind because they're being registered by the web server.
If you want to have a function accessible outside the Code Behind it needs to be registered as a ASMX or WCF service.
See Creating and Consuming Your First WCF Service for setting up a WCF Service.
Once it is setup and running you can use Ajax to call the methods just like you would in the Code Behind.
$.ajax({
//Path to WCF Server and Target Method
url: "http://localhost:PORT/wcfsvc/FooService.svc/Foo",
type: 'get',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$(document.body).append(data);
}
});
See also: Consuming WCF from jQuery as JSON
The short answer is "No, it isn't possible." Front-end code (like jQuery and AJAX) run on the client's machine, but C# functions are back-end and run on the server. There's no direct connection between them.
The longer answer is "Not directly, but there are ways to do something similar." Your easiest option is to use AJAX to POST to another controller/action on your server and then process the response. This is close to what you were doing, but you were slightly off. Rather than the url being a function, the url has to be an actual url on your website. Using /Functions/CallTargetFunction as an example, you would then create a controller like this:
public class FunctionsController : Controller
{
public ActionResult CallTargetFunction()
{
return Content(TargetFunction());
}
}
Note that doing this means anyone who visits http://yoursite.com/Functions/CallTargetFunction will get the result of that function.

Categories

Resources