How to upload with other parameters on jQuery&Javascript Mvc - javascript

With the help of an input, I want to upload photos using the ajaxPost method. The code you tried is as follows.
HTML;
<input type="file" class="form-control" id="update-category-photo" accept=".jpg,.png,.gif,.JPEG,.JPG" />
Javascript;
function updateCategory() {
var fileUpload = $("#update-category-photo").get(0);
var files = fileUpload.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('categoryImage', files[i]);
}
postAjax("/Admin/Category/UpdateCategory", {
categoryName: $("#update-category-name").val(),
categoryId: $("#update-category-id").val(),
formData
} , function (result) {
console.log(result);
});
}
And base:> Admin/Category Controller
[HttpPost]
public JsonResult UpdateCategory(int categoryId, string categoryName)
{
return Json("ok:" + Request.Files.Count, 0);//just test now
}
When I just want to post, I get the error "Uncaught TypeError: Illegal invocation".

this answer;
var file = $("#update-category-photo").get(0).files;
var data = new FormData();
data.append("CategoryPhoto", file[0]);
data.append("CategoryId", $("#update-category-id").val());
data.append("CategoryName", $("#update-category-name").val());
$.ajax({
type: 'POST',
url: '/Admin/Category/UpdateCategory',
data: data,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
}
});
And use ViewModel on controller action

Related

how to append model object to formData in AJAX and retrieve using asp.net

I developed an Ajax POST method to pass the data to the controller. First I append my uploaded file to formData. Then I want to bind a model object to it. I did it. But in the controller, my model is always null.
Please help me how to append correctly and get the model and file correctly
javascript function:
var $file = document.getElementById('file'),
$formData = new FormData();
if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
$formData.append('file-' + i, $file.files[i]);
}
}
var SnapShotReceivedData = [{
REASON: REASON_EXEMPT,
COMMENT: COMMENT_EXEMPT,
ATTACHMENT: $formData
}];
SnapShotReceivedData = JSON.stringify({ 'SnapShotReceivedData': SnapShotReceivedData})
$formData.append('SnapShotReceivedData',SnapShotReceivedData);
$.ajax({
contentType: false;
processData: false,
type: 'POST',
url: '#Url.Action("SetHCMNIDSnapData", "Home")',
data: $formData ,
success: function (result) {
},
failure: function (response) {
// $('#result').html(response);
}
});
Controller:
public JsonResult SetHCMNIDSnapData(List<SnapShot> SnapShotReceivedData)
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
var _file = Request.Files[file];
}
}
}
my model is SnapShotReceivedData.When I debug the controller, the model object always null. please help me to solve this.

Download file from DB with ajax call MVC

I'm trying to implement file download functionality thru ajax call in MVC.
After calling of controller method i always have a "parseerror", can somebody explain me why?
my ajax:
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
$.ajax({
type: "POST",
url: "/File/FileDownload",
//contentType: false,
//processData: false,
//dataType: "json",
data: { fileId: id },
success: function (data) {
$('#uploadStatus').html("ok");
},
error: function (err) {
alert(err.statusText);
}
});
});
and controller:
[HttpPost]
public FileResult FileDownload(int? fileId)
{
FileDBEntities db = new FileDBEntities();
tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
return File(file.Data, file.ContentType, file.Name);
}
with simple download link in razor it works, but not with ajax.
What am I doing wrong here?
Why not simple use
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
window.location = window.location.origin + '/File/FileDownload?fileId=' + id;
});
[HttpGet]
public FileResult FileDownload(int? fileId)

How to achieve File upload using WEB API Dot net core?

I am working on ASP DOT NET core web api where I need to send multiple attachments. I tried like following
<input type="text" id="txt_firstName" />
<input type="text" id="txt_lastName" />
<input type="file" id="file_TicketManageMent_AttachFile" multiple />
<input type="button" onclick="fnADD()" />
<script>
function fnADD(){
var input = document.getElementById('file_TicketManageMent_AttachFile');
var files = fileList;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
var mdl = {};
mdl.FirstName = 'Title';
mdl.LastName = 'Short Description';
mdl.Attachments = formData;
$.ajax({
cache: false,
type: 'Post',
contentType: 'application/json',
data: JSON.stringify(mdl),
url: fnApiRequestUri('api/Customer/AddTicket'),
success: function (xhr, ajaxOptions, thrownError) {
}
});
}
</script>
//C# code
[Route("AddTicket")]
[HttpPost]
[Authorize(Roles = MethodsAuthorization.AllRoles)]
public async Task<IActionResult> AddTicket(Model _model)
{
}
public class Model
{
public string FirstName {get;set;}
public string LastName {get;set;}
public List<IFormFile> Attachments { get; set; }
}
I am getting following error
the server responded with a status of 400 ()
I referred following question
[1]: https://stackoverflow.com/a/49966788/9491935
working on ASP DOT NET core web api where I need to send multiple attachments
To achieve it, you can try to modify the code like below.
Js client
function fnADD() {
var input = document.getElementById('file_TicketManageMent_AttachFile');
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("Attachments", files[i]);
}
formData.append("FirstName", 'Title');
formData.append("LastName", 'Short Description');
$.ajax({
cache: false,
type: 'Post',
data: formData,
url: '{your_url_here}',
processData: false,
contentType: false,
success: function (xhr, ajaxOptions, thrownError) {
}
});
}
Controller action
[Route("AddTicket")]
[HttpPost]
[Authorize(Roles = MethodsAuthorization.AllRoles)]
public async Task<IActionResult> AddTicket([FromForm]Model _model)
{
//code logic here
}
Test Result
<input type="text" id="txt_firstName" />
<input type="text" id="txt_lastName" />
<input type="file" id="file_TicketManageMent_AttachFile" multiple />
<input type="button" onclick="fnADD()" />
<script>
function fnADD(){
var input = document.getElementById('file_TicketManageMent_AttachFile');
var files = fileList;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
formData.append("FirstName ", 'Title');
formData.append("LastName ", 'Short Description');
$.ajax({
cache: false,
type: 'Post',
data: formData,
url: fnApiRequestUri('api/Customer/AddTicket'),
processData: false,
contentType: false,
success: function (xhr, ajaxOptions, thrownError) {
}
});
}
</script>
//C# code
[Route("AddTicket")]
[HttpPost]
[Authorize(Roles = MethodsAuthorization.AllRoles)]
public async Task<IActionResult> AddTicket(Model _model)
{
var files = Request.Form.Files;
foreach(var item in files)
{
var file = item;
if (file != null)
{
var fileName = file.FileName;
if (System.IO.File.Exists(path + fileName))
{
fileName = $"{DateTime.Now.ToString("ddMMyyyyHHmmssfff")}-{fileName}";
}
using (var fileStream = new FileStream(path + fileName, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
reg.Picture = fileName;
}
}
}
public class Model
{
public string FirstName {get;set;}
public string LastName {get;set;}
public List<IFormFile> Attachments { get; set; }
}

Pass array from client side to service side c#

I am calling a javascript function on button click using onclientclick with below function.
function addValues() {
debugger;
var arrValue = [];
var hdnValue = document.getElementById("hdn").value;
var strValue = hdnValue.split(',');
for (var i = 0; i < strValue.length; i++) {
var ddlValue = document.getElementById(strValue[i]).value;
arrValue.push(ddlValue);
}
}
arrValue array will have all the required values and how can I move this array values to server side for further process.
Update 1:
HTML:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
}
$.ajax({
url: '',
data: { ddlArray: arrddlValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
},
error: function (x, e) {
}
});
Code:
protected void btnSort_Click(object sender, EventArgs e)
{
try
{
if (Request["ddlArray[]"] != null)
{
string[] arrValues = Array.ConvertAll(Request["ddlArray[]"].ToString().Split(','), s => (s));
}
}
}
If your framework is ASP.Net you can pass it by $.ajax, I am passing array like:
$.ajax({
url: '',
data: { AbArray: arrValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
and get it in Back-end like:
if (request["AbArray[]"] != null)
{
int[] arrValues = Array.ConvertAll(request["AbArray[]"].ToString().Split(','), s => int.Parse(s));
}
suppose array is int.
the above sample is using Generic-Handler.
if you want to use webmethod do something like:
[WebMethod(EnableSession = true)]
public static void PassArray(List<int> arr)
{
}
and Ajax would be like:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
var jsonVal = JSON.stringify({ arr: arrValue });
$.ajax({
url: 'YourPage.aspx/PassArray',
data: jsonVal,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
}
Change Ajax Url as your PassArray address which mean YourPage.aspx should be change to page name which have PassArray in it's code-behind.
For more info Read This.
If you are using Asp.net WebForm Application,
Approach 1 : you can store your array value in a hidden input control and retrieve the saved data in your c# coding.
Approach 2 : define web method in your server side c# code and pass this javascript array value as ajax call.
link for Approach 1 : https://www.aspsnippets.com/Articles/Pass-JavaScript-variable-value-to-Server-Side-Code-Behind-in-ASPNet-using-C-and-VBNet.aspx
link for Approach 2 : https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx
I would "stringify" the array by imploding it with a special char unlikely to appear in my values (for example: §), and then with the help of jQuery.ajax() function, I will send it to the backend (ASP.NET MVC) action method:
$.ajax({
url : 'http://a-domain.com/MyController/MyAction',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
My backend would be something like this (in MyController class):
[HttpPost]
public ActionResult MyAction(string data)
{
string[] arrValue = data.Split('§');
...
}
UPDATE
For ASP.NET forms, the ajax request would be:
$.ajax({
url : 'http://a-domain.com/MyPage.aspx/MyMethod',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
And the backend would be something like this:
[System.Web.Services.WebMethod]
public static void MyMethod(string data)
{
string[] arrValue = data.Split('§');
...
}
You will find a more precise explanation here: https://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

Form with 2 values and are null

I'm trying to upload a file and the form data using ajax. But I'm getting a formData object with null values.
I can log the fileUpload object corretly but my formData log is empty.
Can someone explain me what's wrong?
$(document).ready(function () {
var formData = new FormData();
$('#fileUpload').change(function () {
formData.append('file',$('#fileUpload')[0].files[0]);
console.log($('#fileUpload')[0].files[0]);
});
$('#btnSubmit').click(function (e) {
e.preventDefault();
formData.append('data',$('#creationForm')[0]);
console.log(formData);
$.ajax({
type: 'post',
url: '/upload/testCase',
data: formData,
processData: false,
success: function (result) {},
error: function () {}
});
return false;
});
});
And I want to use them in Spring Controller.
#RequestMapping(value = "/upload/testCase" , method = RequestMethod.POST)
public #ResponseBody String uploadTestCase(#RequestParam("data") String data, #RequestParam("file") MultipartFile file ) {
//TestCases.upload(file);
System.out.println(data + file);
return "";
}
formData is not null, you are just not inspecting it correctly:
Try this:
$('#fileUpload').change(function () {
formData.append('uploadedFile',$('#fileUpload')[0].files[0]);
// inspect each key/value entry
for (var data of formData.entries()) {
console.log(data[0] + ', ' + data[1]);
}
});

Categories