Export excel on WebAPI and EPPlus with post AJAX - c#

I'm trying to export some data in my page sending a JSON object to my controller, calling this method:
[HttpPost]
public HttpResponseMessage Export([FromBody]List<PivotGridModel> lstPivotGrid)
{
transporte = GetList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content = new ByteArrayContent(_Service.Export(transporte.Lista, lstPivotGrid));
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = String.Format("Plan_{0:yyyy-MM-dd__HH-mm-ss}.xlsx", DateTime.Now);
return response;
}
The AJAX called when I click in the button 'Export' in my page is this one:
// the 'url' is the path of my controller and the 'data' is my object
executePostAjaxDataHeaders: function (url, data, headers) {
var obj = null;
utils.vars.callerName = arguments.callee != null && arguments.callee.caller != null ? arguments.callee.caller.name : "";
$.ajax({
type: "POST",
url: url,
async: false,
data: JSON.stringify(data),
headers: headers,
contentType: 'application/json; charset=utf-8',
beforeSend: function () { dxLoadPanel.funcs.show(); },
complete: function () { dxLoadPanel.funcs.hide(); },
success: function (data) { obj = data; },
error: function (request, status, error) { console.log(request); console.log(error); obj = utils.funcs.loadAjaxError(utils.vars.callerName, request, status, error); }
});
return obj;
}
When I click in the button on my page, the console returns me an error that says:
Error: Invalid XML: some random characteres like: �&N��>�
What am I missing? I wanted to download the file in my page... I was testing it using a 'Get' and calling my controller directly in the URL, but when I changed my method to a post (to get the data on my page) it stopped working.

Related

Why ajax method returning output in incorrect format in ASP.NET using C# and jQuery

I'm returning the simple JSON output using a jQuery Ajax method from an aspx.cs page using [WebMethod] and the output is not returning properly below is my code
using System.Web.Services;
[WebMethod]
public static string Chart_Symbols()
{
string myJsonResponse = "";
try
{
myJsonResponse = "[{\"symbol\":\"AARTIIND\",\"full_name\":\"NSE:AARTIIND\",\"description\":\"AARTI INDUSTRIES LTD\",\"exchange\":\"NSE\",\"ticker\":\"AARTIIND\",\"TYPE\":\"stock\"}]";
}
catch (Exception ex)
{
throw ex;
}
return myJsonResponse;
}
From that [WebMethod], I'm getting this output:
This is my jQuery Ajax method:
//Calling Method
$(document).ready(function () {
var res = FetchingServiceData();
alert(res);
});
//Returning output using Ajax method
function FetchingServiceData() {
var res = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TV_Chart.aspx/Chart_Symbols",
dataType: "json",
data: "{}",
success: function (data) { },
async: false,
error: function (err) {
console.log("eror is ==> "+err);
}
}).responseText;//.then(res => res.json()).then(symbols => {
// console.log("chart_symbol :- " + JSON.parse(symbols));
// return JSON.parse(symbols);
//});
// res = res.replace("{\"d\":\"[{", "[{");
// res = res.replace("}]\"}", "}]");
// res = res.replace("\\", "");
// res = res.replace("\\", "");
// return JSON.stringify(res);
// return JSON.parse(res);
return res;
}
Once I execute the project Ajax method returning the output like this
{"d":"[{\"symbol\":\"AARTIIND\",\"full_name\":\"NSE:AARTIIND\",\"description\":\"AARTI INDUSTRIES LTD\",\"exchange\":\"NSE\",\"ticker\":\"AARTIIND\",\"TYPE\":\"stock\"}]"}
Image output:
But my output should come like this only:
var res = [{ "symbol": "AARTIIND", "full_name": "NSE:AARTIIND", "description": "AARTI INDUSTRIES LTD", "exchange": "NSE", "ticker": "AARTIIND", "TYPE": "stock" }];
Why am I not getting the correct format in the output from my Ajax method?
Can you suggest what my mistake is?
I'm assuming this point: using res = res.replace("",""); is not a good practice.

JQuery ajax success never run

i have this jquery code, sending items to controller and download from controller, everything is fine
downloads is fine, i check response from in Chrome Network Tab is okay. but success function never run after process done. (i'm using async:false; already)
$(document).on('click', '#baslat', function (e) {
var token = $("#token").val();
var islemler = [];
var secililer = [];
$.each($("input[class='cc']:checked"), function () {
var islem = {};
islem.IslemTuru = $(this).attr("id");
islemler.push(islem);
});
$.each($("tr[class='sec']"), function () {
if ($(this).children('td:eq(1)').children("input[type='checkbox']").prop('checked')) {
var beyan = {};
beyan.Id = $(this).attr("id");
beyan.TahakkukId = $(this).data("id");
beyan.KisaKod = $(this).children('td:eq(2)').html();
beyan.BeyannameTuru = $(this).children('td:eq(4)').html();
beyan.Ay = $(this).children('td:eq(5)').html().substring(8, 10);
beyan.Yil = $(this).children('td:eq(5)').html().substring(11, 16);
secililer.push(beyan);
}
});
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string",
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
});
The controller is here. I have to use Thread.Sleep (1000) in the method. because the server on which I want to download files wants 1 second to pass between each request.
public async Task<string> BeyanAl(List<Beyanname> secililer, List<Islem> islemler, string token)
{
bool indir = true;
bool yazdir = false;
bool gonder = false;
foreach (var islem in islemler)
{
if (islem.IslemTuru =="cbyazdir")
{
yazdir = true;
}
if (islem.IslemTuru == "cbgonder")
{
gonder= true;
}
}
foreach (var GelenBeyan in secililer)
{
string YolAdi = YolHazirla(GelenBeyan);
string DosyaAdi = DosyaAdiHazirla(GelenBeyan);
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Beyan", GelenBeyan.Id, "");
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Tahakkuk", GelenBeyan.Id, GelenBeyan.TahakkukId);
}
return "İndirildi";
}
here is chrome response screens
r1
r2
There is no 'string' data type in ajax datatypes make it json or text
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string", <-- make it json or text
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});

i made Jquery ajax call to c# webservice method which return type is void ,while call response goes to error?

I made Jquery ajax call to c# web service method which return type is void, while call response goes to error, instead of success.
What is the solution
Here is the code,
Jquery ajax call :
$.ajax({
type: "POST",
url: "~/MyWebService.asmx/SCheduleDetailsGet",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: false,
//global: false,
success: function (response) {
debugger;
},
error: function (data, xhr, error) {
debugger;
return false;
}
});
C# web service method:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public void SCheduleDetailsGet(int LoginUserID,int ResumeSearchId,string Flag)
{
try
{
DataSet ds = new DataSet();
ds = RHSCheduleGet(LoginUserID, ResumeSearchId, Flag);
object _jsonReturn = null;
object jSonString = null;
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
_jsonReturn = JsonConvert.SerializeObject(ds.Tables[0]);
_jsonReturn = "{\"aaData\":" + _jsonReturn + "}";
Context.Response.Write(_jsonReturn);
}
catch (Exception ex)
{
Context.Response.Write("-2");
}
}

asp net mvc ajax file upload with antiforgerytoken and without formData

I have an asp.net mvc application and want to upload files and form data with ajax and also want to use [ValidateAntiForgeryToken]-Attribute. But i not want use formData class client side (because of brower support).
My client code:
function sendMessage(id) {
if (window.FormData !== undefined) { //
var fileData = new FormData();
fileData.append('profileId', id);
fileData.append('title', $('#Message_Title').val());
fileData.append('text', $('#Message_Text').val());
fileData.append('__RequestVerificationToken', $('[name=__RequestVerificationToken]').val());
var files = $("#Message_Image").get(0).files;
if (files[0]) {
fileData.append(files[0].name, files[0]);
}
$.ajax({
url: '/Manage/SendMessage',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
var files2 = $("#Message_Image").get(0).files;
$.ajax({
url: '/Manage/SendMessage',
type: 'POST',
//contentType: false,
//processData: false,
data: {
profileId: id,
title: $('#Message_Title').val(),
text: $('#Message_Text').val(),
//image: files2[0], <--- IF I UNCOMMENT THIS IT NOT WORKS ANYMORE
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val()
},
success: function (result) {
},
error: function (err) {
alert(err.statusText);
}
});
}
};
Server code:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SendMessage(int? profileId, string title, string text)
{
HttpPostedFileBase file = Request.Files["Image"];
HttpFileCollectionBase files = Request.Files;
return Json(null, "text/html");
}

Sending object to a controller in asp.net mvc using ajax

I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...

Categories