I am able to pass single file as System.Web.HttpPostedFileBase but when i pass same as array of files i am getting null in controller's action.
I've tried sending array of files.
HTML:
<input type="file" id="Attachment1">
<input type="file" id="Attachment2">
<input type="file" id="Attachment3">
<input type="file" id="Attachment4">
<input type="file" id="Attachment5">
Javascript:
var FileData = [];
$('input').each(function () {
var type = $(this).attr("type");
if (type == "file") {
FileData.push($(this).get(0).files[0]);
}
});
var Data = new FormData();
Data.append("Attachments", FileData);
if (url != '') {
$.ajax({
url: url,
data: Data,
type: "POST",
contentType: false,
processData: false,
success: function (data) {
alert("Saved successfully");
}
});
}
Controller:
public ActionResult InsertDetails(System.Web.HttpPostedFileBase[] Attachments)
{
return Json(new { Success = false });
}
Need to get array of files. Thanks in advance.
Thanks for the effort guys. I found the solution. I just need to keep append files for same key "Attachments". Now i am able to get as array of HttpPostedFileBase.
var Data = new FormData();
$('input').each(function () {
var type = $(this).attr("type");
if (type == "file") {
var FileData = $(this).get(0).files[0]);
Data.append("Attachments", FileData);
}
});
Try It:
var Files = new FormData();
$('input').each(function () {
var type = $(this).attr("type");
if (type == "file") {
Files .append("Attachment"+$(this).attr("id"), $(this).get(0).files[0]);
}
});
if (url != '') {
$.ajax({
url: url,
data: Files ,
type: "POST",
contentType: false,
processData: false,
success: function (data) {
alert("Saved successfully");
}
});
}
This is how I used to post array data from javascript to mvc controller, this is going to be a little bit lengthy but I've explained each line with comment, I hope this may help you
javascript:
var formData = new FormData(); //declare formData
var arrayData = []; //declare array and push/append your data to it.
var name="abc";
arrayData.push(name);
//setting ArrayData to Json Object
var AllData = {
getUserData: arrayData
};
//appending Json Object to formdata with the key "mydata"
formData.append("mydata", JSON.stringify(AllData));
//sending formdata through ajax request
$.ajax({
type: "POST",
url: yourURLHere,
processData: false,
contentType: false,
data: formData,
cache: false,
success: function (data) {
//your program logic here
}
});
Controller:
public async Task<HttpResponseMessage> SaveResponse()
{
//receiving json data from the key "mydata" we set earlier
var getData = HttpContext.Current.Request.Params["mydata"];
//deserialize json object (you will need Newtonsoft.Json library)
var model = JsonConvert.DeserializeObject<MyModel>(getData);
//you will get all of your data in model variable
//do what you want to do with that data
}
and here is the model class
public class MyModel
{
//**dataList** will receive array data sent from javascript
public List<MyModel> dataList = new List<MyModel>();
//Remember, whatever your push to array in javascript, should be declared here.
public string name {get;set;}
}
Related
How do we save file in localStorage and later on retrive it and send it on server to save it.
<input id="File1" type="file" onchange="saveLocal();" />
<button type="button" onclick="saveServer()">Sync</button>
<script>
function saveServer()
{
var blob = localStorage.getItem("file");
var form = new FormData();
form.append("file", blob);
AjaxPost("/Grades/test", form, function (data) {
alert(data);
});
}
function saveLocal()
{
var file = $("#File1")[0].files[0];
var reader = new FileReader();
reader.onload = function (e) {
localStorage.setItem("file", reader.result);
$("#File1").val("");
}
reader.readAsDataURL(file);
}
</script>
and server side code is
[HttpPost]
public ActionResult test(HttpPostedFileBase file)
{
return View();
}
when i issue a request file is null how we do that?
You can try to use jquery ajax and set contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it.
processData need to set false too.
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
function saveServer()
{
var blob = localStorage.getItem("file");
var form = new FormData();
form.append("file", blob);
$.ajax({
url: '/Grades/test', //full url
data: form,
type: 'POST',
contentType: false,
processData: false,
success:function(data) {
alert(data);
}
});
}
function saveLocal()
{
var file = $("#File1")[0].files[0];
var reader = new FileReader();
reader.onload = function (e) {
localStorage.setItem("file", reader.result);
$("#File1").val("");
}
reader.readAsDataURL(file);
}
How do I pass a whole set model object through formdata and convert it to model type in the controller?
Below is what I've tried!
JavaScript part:
model = {
EventFromDate: fromDate,
EventToDate: toDate,
ImageUrl: imgUrl,
HotNewsDesc: $("#txthtDescription").val().trim(),
};
formdata.append("model",model);
then pass it through AJAX, it will be a string, and if I check the value of Request.Form["model"] the result will be same, that is it will be received as string and value will be "[object object]"
Is there any way to pass model through formdata and receive it in the controller?
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using
var formdata = new FormData($('form').get(0));
This will also include any files generated with <input type="file" name="myImage" .../>
and post it back using
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
and in your controller
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
formdata.append('someProperty', 'SomeValue');
If you want to send Form data using Ajax.This is the way to send
var formData = new FormData();
//File Upload
var totalFiles = document.getElementById("Iupload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Iupload").files[i];
formData.append("Document", file);
}
formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());
$.ajax({
url: "/Controller/ActionName",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
success: function (result) {
}
})
Using Pure Javascript, considering you have
<form id="FileUploadForm">
<input id="textInput" type="text" />
<input id="fileInput" type="file" name="fileInput" multiple>
<input type="submit" value="Upload file" />
</form>
JS
document.getElementById('FileUploadForm').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//text value
formdata.append("textvalue",document.getElementById("textInput").value);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/UploadFiles');
xhr.send(formdata); // se
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//on success alert response
alert(xhr.responseText);
}
}
return false;
}
in your C# controller you can get values it as below
[HttpPost]
public ActionResult UploadFiles(YourModelType model, HttpPostedFileBase fileInput)
{
//save data in db
}
Reference : File Uploading using jQuery Ajax or Javascript in MVC
In view side ,if you are using ajax then,
$('#button_Id').on('click', function(){
var Datas=JSON.stringify($('form').serialize());
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: '#Url.Action("ActionName","ControllerName")',
data:Datas,
cache: false,
dataType: 'JSON',
async: true,
success: function (data) {
},
});
});
In Controller side,
[HttpPost]
public ActionResult ActionName(ModelName modelObj)
{
//Some code here
}
How do I pass a whole set model object through formdata and convert it to model type in the controller?
Below is what I've tried!
JavaScript part:
model = {
EventFromDate: fromDate,
EventToDate: toDate,
ImageUrl: imgUrl,
HotNewsDesc: $("#txthtDescription").val().trim(),
};
formdata.append("model",model);
then pass it through AJAX, it will be a string, and if I check the value of Request.Form["model"] the result will be same, that is it will be received as string and value will be "[object object]"
Is there any way to pass model through formdata and receive it in the controller?
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using
var formdata = new FormData($('form').get(0));
This will also include any files generated with <input type="file" name="myImage" .../>
and post it back using
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
and in your controller
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
formdata.append('someProperty', 'SomeValue');
If you want to send Form data using Ajax.This is the way to send
var formData = new FormData();
//File Upload
var totalFiles = document.getElementById("Iupload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Iupload").files[i];
formData.append("Document", file);
}
formData.append("NameCode", $('#SelecterID').val());
formData.append("AirLineCode", $('#SelecterID').val());
$.ajax({
url: "/Controller/ActionName",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
success: function (result) {
}
})
Using Pure Javascript, considering you have
<form id="FileUploadForm">
<input id="textInput" type="text" />
<input id="fileInput" type="file" name="fileInput" multiple>
<input type="submit" value="Upload file" />
</form>
JS
document.getElementById('FileUploadForm').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//text value
formdata.append("textvalue",document.getElementById("textInput").value);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/UploadFiles');
xhr.send(formdata); // se
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//on success alert response
alert(xhr.responseText);
}
}
return false;
}
in your C# controller you can get values it as below
[HttpPost]
public ActionResult UploadFiles(YourModelType model, HttpPostedFileBase fileInput)
{
//save data in db
}
Reference : File Uploading using jQuery Ajax or Javascript in MVC
In view side ,if you are using ajax then,
$('#button_Id').on('click', function(){
var Datas=JSON.stringify($('form').serialize());
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
url: '#Url.Action("ActionName","ControllerName")',
data:Datas,
cache: false,
dataType: 'JSON',
async: true,
success: function (data) {
},
});
});
In Controller side,
[HttpPost]
public ActionResult ActionName(ModelName modelObj)
{
//Some code here
}
I need to pass my upload file to my controller using jquery ajax.
JS:
$('#btnpopupreg').click(function () {
$.ajax({
type: 'POST',
url: '/Membership/Register',
data: $('#frmRegister').serializeArray(),
dataType: 'json',
headers: fnGetToken(),
beforeSend: function (xhr) {
},
success: function (data) {
//do something
},
error: function (xhr) {
}
})
})
View:
#model Test.RegisterViewModel
#{
using Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "frmPopUpRegister", .enctype = "multipart/form-data"})
}
<input type="file" />
//rest of my strongly typed model here
<input type="button" value="BUTTON" />
//rest of the code here
Controller:
[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]
public void Register(RegisterViewModel model)
{
if (Request.Files.Count > 0) { //always 0
}
if (ModelState.IsValid) {
//do something with model
}
}
I can get the model value just fine but Request.Files always returns null. I also tried using HttpPostedFileBase but it also always return null
[HttpPost()]
[AllowAnonymous()]
[ValidateAntiForgeryToken()]
public void Register(RegisterViewModel model, HttpPostedFileBase files)
{
//files always null
if (ModelState.IsValid) {
//do something with model
}
}
First you need to give you file control a name attribute so it can post back a value to your controller
<input type="file" name="files" /> //
Then serialize your form and the associated file(s)
var formdata = new FormData($('form').get(0));
and post back with
$.ajax({
url: '#Url.Action("Register", "Membership")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
....
}
});
Note also the file input needs to be inside the form tags
You need to use FormData with combination of contentType, processData setting to false:
var formData = new FormData();
formData.append("userfile", $('#frmRegister input[type="file"]')[0].files[0]);
// append the file in the form data
$.ajax({
type: 'POST',
url: '/Membership/Register',
data: formdata, // send it here
dataType: 'json',
contentType:false, // this
processData:false, // and this should be false in case of uploading files
headers: fnGetToken(),
beforeSend: function(xhr) {
},
success: function(data) {
//do something
},
error: function(xhr) {
}
})
<input type="file" id="LogoImage" name="image" />
<script>
var formData = new FormData($('#frmAddHotelMaster').get(0));
var file = document.getElementById("LogoImage").files[0];
formData.append("file", file);
$.ajax({
type: "POST",
url: '/HotelMaster/SaveHotel',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
swal({
title: "Good job!",
text: "Data Save successfully!",
type: "success"
});
$('#wrapper').empty();
$('#wrapper').append(htmlData);
},
error: function (error) {
alert("errror");
}
});
</script>
public ActionResult SaveHotel(HotelMasterModel viewModel, HttpPostedFileBase file)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
file.SaveAs(path);
}
return View();
}
I am using html2canvs.js for taking screen shots of the page which is described here:
How to take screen shot of current webpage using javascript/jquery
The above process works fine, but now I want to pass the Base64 data to a c# method via ajax. My code looks like:
$('#gbox_Basic').html2canvas({
onrendered: function (canvas) {
var imgString = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "/Home/SentEmail2",
data: //how to pass base64 data 'imgString' ,
contentType: "multipart/form-data",
success: function () {
}
});
}
});
And here is my c# method
public void SentEmail2(what type of param it would accept?) {
//process incoming params
}
Give a try to this:
Controller.cs
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Form
The object FormData will hold the file element to be send.
var formData = new FormData($('form')[0]);
$.ajax({
url: '/Home/SentEmail2', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
References:
http://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/