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

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)
{
}

Related

Passing an Excel file to server using AJAX Post

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

When I try to upload a csv file to controller, it always returns a 404

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

ASP.NET C# Ajax Call Error

I'm going straight to the point here.
I'm trying to get the value pass from my ajax to controller and console.log the value. however, when I try to console.log the value it gives me error 500..
here's my code:
I've been doing ajax on php for a long time.. however, I'm still new to asp.net C# mvc so please bear with me.
AJAX:
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data:{id: province_id},
success: function (data) {
console.log(data);
}
});
});
CONTROLLER:
[HttpPost]
public ActionResult GetCities(int id)
{
return Json(new { success = true });
}
here's the error I don't know what's wrong with my controller though.
POST http://localhost:43969/Property/GetCities 500 (Internal Server
Error)
if using contentType: 'application/json; charset=utf-8' then use JSON.stringify to convert the data being sent to a JSON string.
$("#Property_ProvinceID").on("change", function () {
var $this = $(this);
var province_id = $this.val();
var $url = "/Property/GetCities";
alert("get:" + province_id);
var data = JSON.stringify({id: province_id});
$.ajax({
url: $url,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (data) {
console.log(data);
}
});
});
As mentioned in the comments by #StephenMuecke
It does not need to be stringified if contentType: 'application/json; charset=utf-8', is removed (so that it uses the default application/x-www-form-urlencoded; charset=UTF-8').
you can add error function to check for possible error on your ajax.
Ex.
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}

Pass html string to server side with Jquery Ajax

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

How to use a JSON object created in code behind?

In Info.aspx.cs i get a compressed file from the WebService. After decoding the content i have an xml File. Using XmlToJSON and JavaScriptSerializer the result is a JSON object. How can i use this object in Info.aspx?
Suppose your json is n below format
var A={
propertyOne: "propertyOne",
propertyTwo: "propertyTwo"
}
Use as below:
A.propertyOne
A.propertyTwo
Try this,
var returnValue = new Object();
returnValue.entityfirst = $("#entityfirst ").val();
returnValue.entitysecond = $("#entitysecond ").val();
returnValue.entitythird = $("#entitythird").val();
var request = $.ajax({
url: ..., //access method url
type: 'POST',
cache: false,
data: JSON.stringify(returnValue),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
In you aspx page you have to use javascript if you do a dynamic load.
for example you call and recieve like this (jQuery) :
$.ajax({
url: "myUrlPageForCallJsonService",
type: 'POST',
data: "yourParamsForGettingJson"
dataType: 'json',
complete: function (results) { console.log('complete'); },
success: function (data) { //You logic in the success function
for (var i = 0; i < data.length; i++) {
console.log("success");
_html += '<li>'+ data[i].Param1 + '</li>';
}
_html += '</ul>';
$('#renderbody').html(_html);
},
fail: function (data) { console.log("fail"); }
});
Hope that's help

Categories