Access file using MVC 6 .NET Core with ajax - javascript

I am calling this function to send a file via post:
function AddFileHandler() {
return $.ajax({
processData: false,
contentType: false,
type: "POST",
url: '#Url.Action("AddFile", "SomeController")',
data: getFile()
})
}
In my controller, there is this method which produces an error on the first line:
[HttpPost]
public string AddFile()
{
var attachedFile = Request.Form.Files["CsvDoc"]; // there is an error of wrong contentType
return "";
}
My getFile method optains data like this:
function getFile() {
var input = document.getElementById("csvFile");
if (!input || !input.files || !input.files[0]) {
return ";";
}
console.log(input.files[0]); //inputs my file correctly
var data = new FormData();
data.append("CsvDoc", input.files[0]);
}
What exactly am I doing wrong? Does it matter what is in the html?

You're forgetting to return anything from getFile()
simply add
return data;

Related

Download XML received from controller

I need to download an XML received from a controller, but I need the prompt to write a the name and the location where the file will be saved.
First question: is optimal to send the xml like I did in this code or I should send it like a file in some way.
Second question: receiving the xml or the xml file, how can open the prompt and finally save the xml like a file?
[HttpPost]
public ActionResult ExportFiles(string clientName, string currenthcsystem)
{
try
{
var systemActionsConfigurationData = service.GetHcSystemActionsConfigurationData(clientName,currenthcsystem);
XmlSerializer xsSubmit = new XmlSerializer(typeof(HcSystemActionsConfigurationData));
var xml = "";
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, systemActionsConfigurationData);
xml = sww.ToString();
}
}
return Content(xml, "text/xml");
}
catch (Exception)
{
throw;
}
}
$('#exportButton').on("click", function () {
var clientName = $(actionsButtons).data('clientname');
var currentHCSystem = $(actionsButtons).data('hcsystemname');
// Create FormData object
var parameters = new FormData();
parameters.append("clientName", clientName);
parameters.append("currentHCSystem", currentHCSystem);
$.ajax({
url: $(actionsButtons).data('export'),
type: 'POST',
data: parameters,
cache: false,
processData: false,
contentType: false,
success: function (response) {
//logic to open the prompt and finally download the xml
},
error: function (err) {
}
});
});

JSON Object always return undefined with AJAX

The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept

Get pdf of current page MVC 5

I am trying to get a pdf of a div in my view.
I am doing the following:
I get the element, uri encode its html, then pass it to a method via ajax:
AJAX:
function getPDF(html) {
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) }
}).done(function (result) {
window.open("data:application/pdf; " + result);
$("#printArea").html(result);
}).fail(function (data) {
alert("Failed");
});
}
Method:
[HttpPost]
public void printPage(string html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
//var base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
Response.BinaryWrite(mem.ToArray());
//return File(mem, System.Net.Mime.MediaTypeNames.Application.Octet);
}
In the end I get a popup to open a pdf but it won't open, according to adobe acrobat it is corrupt.
I tried sending the html as a perameter to the method, but the perameter is too long
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
What would be a good way of doing this.
public JsonResult printPage(String html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
mem.Flush();
mem.Position = 0;
String b64Converted = Convert.ToBase64String(mem.ToArray());
return Json(b64Converted, JsonRequestBehavior.AllowGet );
System.Net.Mime.MediaTypeNames.Application.Octet);
}
Then in the view:
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) },
}).done(function (result) {
$("#printArea").append('PDF');
}).fail(function (data) {
alert("Failed");
});
Apparently its very easy
Just base64 the pdf and send it over at the json response.

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

How to pass uploaded image path to controller via ajax [duplicate]

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
When passing uploaded file through ajax to asp.net MVC controller, file property is showing null value in controller.
image file object taken by document.getElementById('fileUpload').files[0] action and convert to JSON.stringify(fileName) but when pass that object to asp.net mvc controller
it is showing null value in mvc controller.
please if any one know how to pass that file to ajax to mvc controller, please post your answer
Admin controller
[HttpPost]
public string AddRetailer(HttpPostedFileBase file, string storeName, string storeUrl, string ecommercePlatform)
{
try {
Bswayed.Admin.Retailer retailer = new Bswayed.Admin.Retailer();
return JsonConvert.SerializeObject(data);
} catch (Exception ex) {
throw ex;
}
}
Asp.net upload form
<input type="file" id="fileUpload" name="fileUpload" onchange="this.parentNode.nextSibling.value = this.value"/>Browse
<input class="input-lg"
#Html.TextBoxFor(Model => Model.StoreLogo, new { placeholder=#ViewBag.StoreLogo})
Java script(Ajax)
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload').files[0]
$.ajax({
url: $("#addRetailer").val(),
cache: false,
type: "POST",
data: {
file:JSON.stringify(fileName),
storeName: storeName,
storeUrl: storeUrl,
ecommercePlatform: ecommercePlatform
},
dataType: "json",
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}
}
You don't need to stringfy uploaded image path. Below code is working in my application. I just used FormData() to get all form. After that added all items in form that i want to send to controller. In this case, you don't need to pass parameter in controller. You can get by Request.Files for image & Request.Form for extra data. I hope, It may helps you. If there is any wrong, then share with me, i will sort it out.
Java Script -
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload')..get(0).files;
var data = new FormData();
if (fileName.length > 0) {
data.append("userUploadedImage", fileName[0]);
data.append("storeName", storeName);
data.append("storeUrl", storeUrl);
data.append("ecommercePlatform", ecommercePlatform);
}
$.ajax({
url: $("#addRetailer").val(),
processData: false,
contentType: false,
type: "POST",
data: data,
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}}
Controller -
[HttpPost]
public string AddRetailer()
{
HttpPostedFileBase image = Request.Files["userUploadedImage"];
string storeName = Request.Form["storeName"];
string storeUrl = Request.Form["storeUrl"];
string ecommercePlatform = Request.Form["ecommercePlatform"];
}

Categories