How to read data from javascript FormData other than file - c#

I need to upload files and some other data, for which I used bellow code
HTML:
<intut type='file' id='file1'>
<intut type='file' id='file2'>
javascript:
var data = new FormData(),
categories = ['node.js','redis'],
roles = ['admin','HR'];
data.Append ($('#file1').Files[0].name, $('#file1').Files[0]);
data.Append ($('#file2').Files[0].name, $('#file2').Files[0]);
data.Append ('category', 'categories');
data.Append ('role', 'roles');
$.ajax({
url: baseaddress + 'DocRepo/GetAdminUploadData',
type: 'Post',
data: data,
cache: false,
dataType: 'json',
async: false,
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
From here I have an action method in my MVC Controller (not webapi) GetAdminUploadData where I need to collect all data(files, category and roles) how can do it.

Assuming that you are only looking for how to get the non-file items (as the title says ... although is not mentioned in the body of the question) and that the server code is C# (as your note from 3-feb-15 hints) I'd say this question is a duplicate of and answered by: How can retrieve string formData js in c#.
Namely: HttpContext.Current.Request.Form["KEY"]

Related

Receive image through ajax post request what should be the class to receive that image

here is my ajax method
fl = new FormData();
fl.append("abcd", $("#so_camera_click")[0].files[0]);
debugger;
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
dataType: "json",
traditional: true,
data: {
f:fl,
}});
and C# controller is
the id so_camera_click is <input type="file" accept="image/*"/> every time i debug javascript there is data in fl variable but when it hits back end c# controller it gets null
public JsonResult AddSaleOrderToDB(HttpPostedFileWrapper f)
{
}
In your ajax request,
Change the value of data as follows,
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
traditional: true,
processData: false,
contentType: false
data: fl
});
Use Proper, readable field names.
Your controller is expecting a File and not a JSON data.
You'll want to post FileData and not json.
Additionally, for the Controller to map your posted values the argument must have the same name as you have used for the POST.
So for your example to work you'll have to do something like this
fl = new FormData();
fl.append("file", $("#so_camera_click")[0].files[0]);
debugger;
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
data: fl,
contentType: false,
processData: false
});
And in your Controller
public JsonResult AddSaleOrderToDB(HttpPostedFileWrapper file)
{
}

Pass parameter from Jquery to webhandler asp.net c#

I want to be able to drag and drop files into multiple folders on a server, I am using jquery to pass to HttpHandler but I can't pass the save location to webhandler. I would like to send the path from jquery in the request is there a way to incluse that when the data for file transfer is passed.
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
Maybe something like this:
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType: false,
processData: false,
data: data,
filepath: document.getElementById("<%=listDrop.ClientID%>");
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
and then retrieve the path in the webhandler to pass as save location?
I have tried this $.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
filepath:JSON.stringify("~/uploads/")
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
}); But I have question about the declaration of the data type for the files I will be uploading when creating the get and set in asp. filepath is a string but what data type are the files.
although i am answering from my mobile, i tried my best to keep the things intact and use ful. If required, Please format it accordingly.
I am not going to write entire code here, just algo.
1. Identify the parameter to be passed. If its only path of multiple folders then you can create an array of objects in javascript for the same. See tge example
var listOfFolder = new string[];
listOfFolder[0]="path of first dir";
:
:
listOfFolder[n]="path of nth dir";
var data = JSON.stringify(listOfFolder);
2. pass this data in data attribute of jquery ajax. 3. Grab this path in Process Request event and deserialize.
4. Do whatever you want.

FileUpload formData in ASP.NET WebForms

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this
It is impossible to call a server method
[WebMethod]
public HttpPostedFileBase Name(HttpPostedFileBase file)
{
string ret = "test";
return file;
}
Errors on the client side no
I wrote jQuery function that need to post form data to server using ajax call.
this is my script:
data.append(self.idFileInput, file[f]);
$.ajax({
type: "POST",
url: "/AddContract.aspx/Name",
data: data,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
}
});
Any tips, link or code example would be useful.
Thank you in advance!
try to use contentType: 'application/json; charset=utf-8',
$.ajax({
type: "POST",
url: "AddContract.aspx/Name",
data: { field1: self.idFileInput, field2 : file[f]} ,
dataType: 'json',//Remove this line this line is causing issue.
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (data) {
}
});
In a previous answer I said something stupid about ASPX not supporting WebMethod calls, which they do.
Now a real answer:
In order to post a file you need to use the ajaxSubmit method. See this reference.

Extract values from Ajax call with XML type in ASP.NET

In PHP, I can call a page like this
var data = {
type: 'simple_data'
};
jQuery.ajax({
url: 'http://www.example.com/haha.php', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
And in the PHP server side page, we catch it like
$type=$_POST['type'];
Pretty simple right! It gives back the XML info and GOAL.
Now I want to do it for ASP.NET pages in same way as PHP. I want to call the ASP.NET page like
var data = {
type: 'simple_data'
};
jQuery.ajax({
url: 'http://www.example.com/haha.aspx', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
So how can I catch the data and extract values in ASP.NET. That means I want the functionality similar to this '$_POST['type']' in ASP.NET. I tried to search but nothing found yet or may be didn't find in the right direction. Can anyone please tell me how can I extract this data from this ajax call with XML??
You can use Request.Form["type"]
It is very easy. You need to pass the method name in your URL parameter like so:
jQuery.ajax({
url: 'http://www.example.com/haha.aspx/MethodName', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
ASP.Net will know how to handle the web request and parse the data. You can write something on the .aspx page as simple as:
[WebMethod]
public static string MethodName(string type)
{
// do work with type
}

Data Format Jquery Ajax Post Cross Domain Call Asp.Net MVC method

I am trying $.ajax post MVC call from http to https cross domain.
Client Side
enter code here
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: '{name:"John"}',
dataType: "json",
success: function (data) { pdata = data; }
});
Server Side
[RequireHttps]
[HttpPost]
public string VerifyEmail(string name){
return "got it"
}
I have added Access-Control-Allow-Origin to web.config so the call can be established fine. Now the problem is on server side I got variable name = null
I have also checked debugging and found the data has actually been send to server
HttpContext.Request.Form
{%7bname%3a%22hello%22%7d}
[System.Web.HttpValueCollection]: {%7bname%3a%22hello%22%7d}
The question is how I could retrieve it from the web method?
%7bname%3a%22hello%22%7d This is HTML entity String please Decode the String then parse for JSON.
I think you can change your call to
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: 'John',
dataType: "text",
success: function (data) { pdata = data; }
});

Categories

Resources