How to pass multipart/form-data to c# method via Ajax - c#

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/

Related

Send array of files from Jquery ajax to controller action

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;}
}

MVC RedirectToAction Doesn't Work After JSON Post Return

I am trying to change the page after post process of the AJAX process which executes by MVC. I have used it different way maybe my usage might be wrong.
C# MVC code part. I am sending int list which is user list and process and do something.
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
My problem is redirect part do not work after the MVC process ends. Process works, only redirect doesn't.
JavaScript code here
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
Added this to AJAX and it is not working too
success: function() {
window.location.href = "#Url.Content("~/Courses/Index")";
}
Once you are using AJAX the browser is unaware of the response.
The AJAX success in its current form failed because redirect response code is not in the 2xx status but 3xx
You would need to check the actual response and perform the redirect manually based on the location sent in the redirect response.
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
Update
Working part for anyone who need asap:
Controller Part:
return RedirectToAction("Index","Courses");
Html part:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "#Url.Content("~/Courses/Index")";
}
});
Just deleted
dataType: 'json'
Part because I am using my own data type instead of JSON.

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

Send file with ajax of jQuery to web service in C# (asmx)

I'm using web service with this method:
$.ajax({
type: 'POST',
url: 'page.asmx/method',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{}'
});
Sending json string, and it works, but if I try to append with FormData the content of input and passing it in data value I have 500 response. What have I to do?
You need to serialize you data....
var data = new FormData();
var files = $("#YOURUPLOADCTRLID").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/fileupload/uploadfile",
contentType: false,
processData: false,
data: data
});
And inside the controller you can have something like
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
Hope it helps...
You can send form object like : new FormData($(this)[0]) which send both input values and file object to the ajax call.
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'page.asmx/method',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
Send Client side value server side through jquery and ajax call.
Click On butto send value client side to server side
<script>
$(document).ready(function () {
$("#additembtn").click(function () {
jQuery.ajax({
url: '/TelePhone/Edit',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
Name: $('#txtUsername').val(),
Address: $('#txtAddress').val(),
},
error: function (request, status, error) {
},
sucess: function (data, status, request) {
}
})
});
});
</script>
// Web Servics Telephone.asmx
[HttpPost]
public ActionResult Edit(string data)
{
}

Sending csv through Ajax

I'm trying to senda csv file opened with JS to the method written in C# where csv file will be parsed and added to database.
I have no problem with opening file and getting its contents.
But whatever I do with my Ajax call I receive empty data in the method CreateFromFile.
here you can see my code:
var a = fr.result;
$.ajax({
url: "/DeviceInstance/CreateFromFile",
type: "POST",
datatype: "html",
data: a,
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są nikalne " + data);
},
success: function (data) {
if (data.length > 0) {
alert(data);
}
else {
alert("Operacja zakonczona sukcesem")
}
}
});
and:
[HttpPost]
public JsonResult CreateFromFile(object data)
{
return Json("Sukces");
}
I'm asking how should i modify my code to make things work?
here : fr.result:
samsung;galaxy ;s3;1234567
samsung;galaxy ;s4;54321
samsung;galaxy ;s5;34567yu8
You could read the request input stream to access the body payload:
[HttpPost]
public JsonResult CreateFromFile()
{
byte[] data = new byte[Request.InputStream.Length];
Request.InputStream.Read(data, 0, data.Length);
string csv = Encoding.UTF8.GetString(data);
// ... do something with the csv
return Json("Sukces");
}
Also in your AJAX request you seem to have specified datatype: "html". There are 2 problems with this:
The parameter is called dataType instead of datatype.
You specified html but your controller action returns JSON.
So that's very inconsistent thing. I would recommend you to get rid of this parameter and leave jQuery use the response Content-Type header to automatically infer the correct type.
Try the following (assuming your a payload is really a string):
$.ajax({
url: '/DeviceInstance/CreateFromFile',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ dane: a }),
/* callbacks */
});
And your controller action should now look like the following:
[HttpPost]
public JsonResult CreateFromFile(string dane)
{
// Parse CSV data from "dane"
}
Hope this helps.

Categories