ajax posting formdata error status 200 OK - c#

I am trying to upload file using Ajax.
The Error status is 200 ok .
Response text is my MasterPage HTML Code.
The Request never went to the Back-end as i am debugging with a breakpoint into the method.
so far i have tried this.
C# WebMethod
[HttpPost]
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
file.SaveAs(path);
}
}`
Ajax Request
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});

in ajax call you have to delete dataType: json because files must be sent multipart/form-data
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});

Please try this code
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return reader.result;
};
reader.onerror = function (error) {
return '';
};
}
function uploadFiles() {
var files=[];
$.each(files, function (key, value) {
var x=getBase64(value)
if(!!x)
files.push(x);
});
$.ajax({
type: 'POST',
url: '/Home.aspx/Upload',
data: JSON.stringity({files:files}),
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
[System.Web.Services.WebMethod]
public static void Upload(string[] files)
{
//Convert base64 to file format and save
}

Related

Not Receiving the query result to ajax function from asmx page asp.net

I'm working with the Ajax and jQuery in my app. When I return a query result it's not showing me that result. The Code is given below:
asmx page Code
[WebMethod, ScriptMethod]
public void Getusertimelist(string id)
{
List<UserhoursList> employeelist = new List<UserhoursList>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString))
{
con.Open();
SqlCommand command12 = new SqlCommand(" SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, Total_time) * 3600 ) + ( DATEPART(mi, Total_time) * 60 ) + DATEPART(ss, Total_time)), 0)) From Todaywork Where Id='"+id+"'", con);
string getvalue = command12.ExecuteScalar().ToString();
UserhoursList employee = new UserhoursList();
employee.Total_Time = getvalue;
employeelist.Add(employee);
con.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employeelist));
//return id;
}
Ajax Code
<script type="text/javascript">
$(document).on("click", ".get_time", function () {
var timeid = $(this).data('id');
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: { id: timeid },
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
});
$(document).ready(function () {
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
});
});
</script>
It's not showing me the answer because when I remove that (string id) parameter then it works perfectly. When I use it's not showing me the answer. I want to complete my project but this error not pushing me. Any help plz.
Your first request looks good. But in your second request, I don't see that you're using the jQuery DataTable data option.
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
// Where is data: { id: timeid }?
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
I think it will work if you change data to send a string
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: '{ "id": ' + timeid + '}',
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
an alternative is do something like
var dat = {}
dat.id = timeid
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: JSON.stringify(dat),
success: function (data) {
//alert(data);
},
error: function (err) {
}
});

asp net mvc ajax file upload with antiforgerytoken and without formData

I have an asp.net mvc application and want to upload files and form data with ajax and also want to use [ValidateAntiForgeryToken]-Attribute. But i not want use formData class client side (because of brower support).
My client code:
function sendMessage(id) {
if (window.FormData !== undefined) { //
var fileData = new FormData();
fileData.append('profileId', id);
fileData.append('title', $('#Message_Title').val());
fileData.append('text', $('#Message_Text').val());
fileData.append('__RequestVerificationToken', $('[name=__RequestVerificationToken]').val());
var files = $("#Message_Image").get(0).files;
if (files[0]) {
fileData.append(files[0].name, files[0]);
}
$.ajax({
url: '/Manage/SendMessage',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
var files2 = $("#Message_Image").get(0).files;
$.ajax({
url: '/Manage/SendMessage',
type: 'POST',
//contentType: false,
//processData: false,
data: {
profileId: id,
title: $('#Message_Title').val(),
text: $('#Message_Text').val(),
//image: files2[0], <--- IF I UNCOMMENT THIS IT NOT WORKS ANYMORE
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val()
},
success: function (result) {
},
error: function (err) {
alert(err.statusText);
}
});
}
};
Server code:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SendMessage(int? profileId, string title, string text)
{
HttpPostedFileBase file = Request.Files["Image"];
HttpFileCollectionBase files = Request.Files;
return Json(null, "text/html");
}

File download not working in asp.net mvc 4 [duplicate]

This question already has answers here:
Download Excel file via AJAX MVC
(15 answers)
Closed 6 years ago.
I am new to mvc4 . I used the below code to download file from server to client in the controller:
public ActionResult IndexSpecification(int option_id)
{
int cat = (int)Session["category_Name"];
int prod = (int)Session["product_ID"];
int user = (int)Session["logged_in"];
string twoinone = cat + "_" + prod;
f1 = Download(twoinone);
return f1;
}
where Download function is:
public FileResult Download( string twoinone)
{
var webClient = new WebClient();
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(Server.MapPath("~/Download"), "a.rar"));
string fileName = "Tellersoft.rar";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
The call to the controller is from ajax :
$.ajax({
type: "POST",
url: base_url + '/Options/IndexSpecification',
data: { option_id : 2 },
//dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof (console) != 'undefined') {
alert("oooppss");
} else {
alert("something went wrong");
}
}
});
But downloading not working .not even returning any error. Please help
$.ajax({
type: "POST",
url: base_url + '/Options/IndexSpecification',
data: { option_id : 2 },
//dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof (console) != 'undefined') {
alert("oooppss");
} else {
alert("something went wrong");
}
}
});
In your ajax request in success block you have to write this code:
$.ajax({
type: "POST",
url:'/Home/Download',
data: { option_id: 2 },
//dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
window.location = '/Home/Download?option_id=2';
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof (console) != 'undefined') {
alert("oooppss");
} else {
alert("something went wrong");
}
}
});
you have to set your option id value globally and declare it in success section...
enter image description here

angularjs and webmethod return json

When I use jquery $ajax, I get the data as json
But when using angular http service, I get the response as xml.
This is my both code (angular and jquery ajax)
var _getList = function () {
var list = [];
var deferred = $q.defer();
$.ajax({
type: "POST",
url: '/Landing/manage/WebService.asmx/GetList',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data && data.d) {
list = data.d;
deferred.resolve(list);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
deferred.reject(xmlHttpRequest);
}
});
//angular
$http({
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": "application/json"
}
}).success(function (data) {
console.log(data);
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
And this is my web method code With json format return
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat =
System.Web.Script.Services.ResponseFormat.Json)]
public tblCampaignCollection GetList()
{
tblCampaignCollection coll = Campaign.AdminGetAll();
return coll;
}
The request you are performing is not a real POST Request, I had a similar issue, if you read the console network TAB you will see that it is a GET request.
What I do if I want to perform a POST in a service is the following:
function myService(xxxParam) {
var request = $http({
method: 'POST',
headers: {"Content-Type": 'text/plain; charset=UTF-8'},
url: serviceURL,
data: {
firstPostParam: "string",
secondPostParam: 1,
thirdPostParam: xxxParam
}
});
return ( request.then(handleSuccess, handleError) );
}
try with
$http({
method: 'POST',
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": 'application/json; charset=UTF-8'
},
data: {
dataType: "json"
}
})...
I hope it helps.

Call WebMethod using jQuery

Hi i want to pass the values from jQuery and assign those values to a class model which is used in a method.
Following is my script:
$(document).ready(function(){
$('#BtnSubmit').click(function () {
var CollegeName = $('#TxtCollegeName').val();
var CollegeAddress = $('#TxtCollegeAddress').val();
var pageUrl = '<%=ResolveUrl("~/AddNewCollege.aspx/CreateCollegeData")%>';
$.ajax({
type: 'Post',
url: pageUrl,
data: JSON.stringify({ "CollegeName": CollegeName, "CollegeAddress": CollegeAddress}),
dataType: 'text',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
},
error: function () {
alert("An error occurred.");
}
});
});
});
Below is my Csharp method:
[WebMethod]
public static string CreateCollegeData(CollegeDetails collegeDetails)
{
CollegeDAL obj = new CollegeDAL();
bool b = obj.InsertCollegeDetails(collegeDetails);
return "success";
}
But debugger is unable to call the web method. Every time the following message is coming:
Try declaring your object ahead of time: link
I got another solution.
$('#BtnSubmit').click(function () {
var collegeDetails = {};
collegeDetails.CollegeName = $('#TxtCollegeName').val();
collegeDetails.CollegeAddress = $('#TxtCollegeAddress').val();
$.ajax({
type: 'POST',
url: 'AddNewCollege.aspx/CreateCollegeData',
data: "{collegeDetails:" + JSON.stringify(collegeDetails) + "}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
$('#TxtCollegeName').val('');
$('#TxtCollegeAddress').val('');
},
error: function () {
alert("An error occurred.");
}
});
});

Categories