I am trying to send the 'file' attachment to handler(and send it with email)
This is the code I am using to send it to handler(JS)
When I debug it I see the right values including the file(debug in java-script).
function sendCv_click() {
var settings = {
'data': getData("sendCv"),
'url': "Handlers/SendCV.ashx",
'contentType': 'false',
'processData': 'false'
};
sendCV(settings);
};
function getData(){
data = {
'fullName': $('#txt_sendCv_fullName').val(),
'cvFile':$('#fu_sendCv_upload')[0].files[0],
'email': $('#txt_sendCv_email').val(),
'checkBox': $('#sendCv_chkBox:checked').length
}
function sendCV(settings) {
$.ajax({
type: "POST",
contentType: settings.contentType,
processData: settings.processData,
data: settings.data,
url: settings.url,
dataType: "json",
success: function(data) {
...
},
error: function(data, xhr) {
...
});
}).always(function() {
...
});
}
}
How can I get them in the handler page?
like that I get them as Null, why?
public void ProcessRequest(HttpContext context)
{
string fullName = context.Request.Form.Get("fullName"); //It's Null
string email = context.Request.Form.Get("email");//It's Null
string chkBox_ad = context.Request.Form.Get("checkBox"); //It's Null
/////how can i get the file here ??
bool mailSent = Mail.SendCV(fullName, email, chkBox_ad);
context.Response.ContentType = "text/plain";
if (mailSent)
{
context.Response.Write("true");
}
else
{
context.Response.Write("false");
}
}
This might work...
var postedFile = context.Request.Files[0];
var parser = new MultipartParser(context.Request.InputStream);
if (parser.Success) {
byte[] content = parser.FileContents;
string filename = parser.Filename;
}
MultipartParser is opensource class - see http://multipartparser.codeplex.com/SourceControl/latest#MultipartParser.cs
Related
I am trying to export selected records in to a file and reload the page to update the records in a current view. I am calling web api asynchronously to get all the records. An AJAX call is executing an action in a controller successfully and returning expected data without any error but none of the 'success', 'complete' or 'error' part of ajax function is executing. There are no errors in a developer tool of the browser, no exception, nothing unusual so its getting trickier for me to investigate this issue further. Can I request your a suggestions on this please? Thanks
View :
#Html.ActionLink("Export records", "Index", null, new { Id = "myExportLinkId")
Script :
$("a#myExportLinkId").click(function (e) {
var selected = "";
$('input#myCheckBoxList').each(function () {
if (this.checked == true) {
selected += $(this).val() + ',';
}
});
if (selected != "") {
$.ajax({
url: '/MyController/MyAction',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'MyString': 'stringValue'
},
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
})
And the action/method looks like this :
[HttpGet]
public async Task<ActionResult> ExportNewOrders(string OrderIdString)
{
//code to create and store file
//actually want to send the file details as json/jsonResult but for testing only returning
//string here
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
}
Finally I have resolved this with Promisify functionality of an AJAX call. Obviously the json response I was returning had an issue so I have replaced
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
to
return new JsonResult(){
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
which has fixed the bug and the success function of ajax call got executed.
But other than this there were issues to wait until the file download (which involved encryption decryption, server validations etc) completes and then refresh the page. This I have resolved by implementing an ajax call with Promisify fuctionality. You can find codepen example here and the original post here.
Here is the complete code.
View/HTML
#Html.ActionLink("Export", "yourActionName", null, new { Id = "exportRequest", #onclick = "letMeKnowMyFileIsDownloaded();" })
Script/Ajax
function letMeKnowMyFileIsDownloaded() {
return new Promise(function (resolve, reject) {
$("a#exportRequest").on("click", function () {
$.ajax({
url: this.href + "?param=whatever params you want to pass",
dataType: "json",
data: {
'param1': 'value'
},
success: function (data) {
var a = document.createElement("a");
var url = '/yourControllerName/Download?fileGuid=' + data.guid + '&filename=' + data.fileName;//window.URL.createObjectURL(data);
a.href = url;
a.download = data.fileName;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
resolve(true);
},
error: function (error) {
reject(error);
}
});
});
});
}
letMeKnowMyFileIsDownloaded()
.then(function (bool) {
if (bool) {
//alert("File downloaded 👇");
window.location.reload(1);
}
})
.catch(function (error) {
alert("error");
});
I have used nuget package ClosedXML to handle excel file functionality. Using the stream to create and download the data in excel file without storing the file physically on the server.
And in the controller
//can be async or sync action
public async Task<ActionResult> Index(YourModel model)
{
//do stuff you want
var exportOrders = your_object;
//using DataTable as datasource
var dataSource = new DataTable();
//write your own function to convert your_object to your_dataSource_type
dataSource = FormatTypeToDataTable(exportOrders);
if (dataSource != null && dataSource.Rows.Count > 0)
{
//install ClosedXML.Excel from nuget
using (XLWorkbook wb = new XLWorkbook())
{
try
{
var handle = Guid.NewGuid().ToString();
wb.Worksheets.Add(dataSource, "anyNameForSheet");
string exportFileName = "yourFileName" + ".xlsx";
MemoryStream stream = GetStream(wb);
TempData[handle] = stream; exportFileName);
return new JsonResult()
{
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
//ModelState.AddModelError("", ex.Message);
}
}
}
}
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
var stream = TempData[fileGuid] as MemoryStream;
var data = stream.ToArray();
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
return new EmptyResult();
}
}
I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}
I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}
I was trying to get the base64 post in my codebehind webmethod,
but it seems like everytime I include the base64 I get an error : the server responded with a status of 500 (Internal Server Error) - it keeps on hitting the error function.
The Post works with the other strings when the base64 is not inlcuded int the data that im passing.
function event_create() {
alert("alert test : function works => onclick");
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var eventTitle = $("#eventTitle").val();
var eventDesc = $("#eventDesc").val();
var eventTimeStart = $("#eventTimeStart").val();
var eventTimeEnd = $("#eventTimeEnd").val();
var eventDateStart = $("#eventDateStart").val();
var eventDateEnd = $("#eventDateEnd").val();
var eventType = $("#eventType").val();
var eventPlace = $("#eventPlace").val();
var eventAttendee = document.getElementById("lblSelected").innerText;
var userID = sessionStorage.getItem("userID");
var imageBase64 = getBase64(document.getElementById('test').files[0]);
var data = { 'eventTitle': eventTitle, 'eventDesc': eventDesc, 'eventPlace': eventPlace, 'eventType': eventType, 'eventAttendee': eventAttendee, 'userID': userID, 'imageBase64': imageBase64};
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: ".../../../../Operation/insert.aspx/createEvent",
data: JSON.stringify(data),
datatype: "json",
success: function (result) {
if (result.d <= 0) {
//false alert something
alert("FALSE");
}
else if (result.d > 0) {
//true
alert(result.d);
}
else {
alert("sent but no call-back");
}
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" connection to the server failed ");
console.log("error: " + errorthrown);
}
});
}
Here's the Webmethod that will get the post
[WebMethod(EnableSession = true)]
public static string createEvent(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string userID, string imageBase64)
{
String orgID = (String)HttpContext.Current.Session["orgID"];
string response = orgID;
string path = HttpContext.Current.Server.MapPath("~/Users/Organizer/organizerData/"); // de path
//Check if directory exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = "event1" + ".jpg";// for instance
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(imageBase64);
File.WriteAllBytes(imgPath, imageBytes); //write the file in the directory
return imageBase64;
}
my project is an MVC Web application I am using ajax call to get a huge list of data as JSON.
Here is the code( i am not sure what I a missing ):
$.ajax({
url: url, //server
type: "POST",
async: true,
data: { id: id },
dataType: "json",
success: function (data) {
debugger;
jQuery.each(data, function (i, val) {
//Success code
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
window.baseShowModalOkCancel("<p>Backlog Data</p>", "<p>Error in Database</p>", "ERROR");
}
});
}
Action Controller:( This is a post method in return statement I can see the list of object with the data.
[HttpPost]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult GetBacklogWithData(string id)
{
using (var db = new LiensTrackerEntities())
{
List<BackLogDataList> backLogData = new List<BackLogDataList>();
List<BackLogData> backLog;
backLog = db.BackLogDatas.OrderBy(x =>x.CaseNumber).ToList();
foreach (var item in backLog)
{
BackLogDataList backLogDataList = new BackLogDataList
{
FileNo = item.FileNo,
BackLogId = item.BackLogID,
FirstName = item.FirstName,
LastName = item.LastName,
Middle = item.Middle,
Suffix = item.Suffix,
Address = item.Address,
Address2 = item.Address2,
City = item.City,
St = item.ST,
Zip = item.SP1ZIP,
AmaesRecordCreatedDate = item.AMAESRecordCreatedDate != null ? item.AMAESRecordCreatedDate.ToString().Split(' ')[0] : null,
AddedInRecipient = item.AddedInRecipient
};
backLogData.Add(backLogDataList);
}
}
return Json(backLogData, JsonRequestBehavior.AllowGet);
}
}
It returns with 200 ok but execute the error function when i look into console i found the following error:
Thee error is due to max json string length. the solution is
MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer