I simply want to be able to use a html Input type="file" to select an Excel file
<input type="file" id="UploadedFile" name="UploadedFile" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
then pass that chosen file back to the server - preferably using AJAX post:
var serviceURL = appRoot + 'Register/ImportTasks'
$j.ajax({
type: "post",
url: serviceURL,
data: (??? Not sure how to present here ???),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Specifically I cannot see how I present the 'file' to the AJAX call as data.
public void ImportTasks(DataType?? uploadedExcelFile)
{
..... Doing stuff ...
}
And then I am unsure as to what parameter datatype I should then tell the Method to expect when it is called?
Here is a basic example. You should use FormData
var formData = new FormData();
var uploadFiles = document.getElementById('js-upload-files').files;
this.formData.append("MyKey", uploadFiles[0]);
$.ajax({
type: "POST",
url: 'Controller/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
complete: this.onComplete.bind(this)
});
Edit
Forgot controller code
[HttpPost]
public virtual BetterJsonResult Upload()
{
foreach (var fileKey in Request.Files)
{
...Request.Files[fileKey.ToString()] //access it like this
}
}
Related
When I try to upload a csv file to my controller, it always returns 404. I've tried to add, remove, and replace ajax call properties, but nothing solves the problem.
js code
data = new FormData();
data.append("Csv", files[0]);
$.ajax({
url: '/Home/Parse',
enctype: 'multipart/form-data',
type: 'POST',
data: data,
processData: false,
contentType: false,
async: true,
dataType: 'json',
success: function (resp) {
if (resp) {
debugger;
}
}
});
c# code
[HttpPost]
public IActionResult Parse(IFormFile Csv)
{
Db.Db.ParseCsv(Csv);
return View();
}
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)
{
}
I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue
Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source
i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});
I am trying to pass the contents of a javascript variable to the server for processing. I can pass static strings no problem but when I pass a variable containing a string, the WebMethod is not called. Here is my code:
(Client)
function expand(checkbox)
{
var selectedrow = checkbox.parentNode.parentNode;
var rowindex = selectedrow.rowIndex;
var parent = document.getElementById("parentTable");
var NextRow = parent.rows[rowindex + 1];
var cols = selectedrow.cells[1];
var ID = cols.firstElementChild.attributes.value;
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: "{sendData: ID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
NextRow.style.visibility = "visible";
}
(Server)
[WebMethod]
public static string childBind(string sendData)
{
return String.Format("Hello");
}
Now, if I were to try data: "{sendData: "ok"}", the WebMethod gets called and returns a response. How is my syntax wrong?
You don't have to pass it as a string. Since ID is a javascript variable you have to pass its value. When you pass data as "{sendData: ID}" it will not pass the value of ID.
Try this
data: { sendData: ID }
You were sending a string instead of an object ("{sendData: ID}" instead of {sendData: ID}). And the data you were sending wasn't JSON. So remove the contentType line and change the data line. You should re-write this as:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: {sendData: ID},
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})
You can also write this, if you want to send JSON:
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: $.getJSON({sendData: ID}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) { alert("successful!" + result.d); }
})
Since you are using jQuery run these tests for the answer:
var ID = 45;
var x = "{sendData: ID}";
alert(jQuery.isPlainObject(x)); // false
var y = { sendData: ID};
alert(jQuery.isPlainObject(y)); // true
Here is the jsFiddle:
http://jsfiddle.net/3ugKE/
You are passing in 'ID' as a string rather than a variable.
All you need to do is remove the quotes around your data object.
Further reading on JSON and javascript objects:
http://www.json.org/
http://www.w3schools.com/js/js_objects.asp
you can use this code :
$.ajax({
type: "post",
url: "Playground.aspx/childBind",
data: JSON.stringify({sendData: ID}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { alert("successful!" + result.d); }
})