Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an ASP.NET c# page that will post information of form with AJAX in JSON format.
This information includes text of Texboxes and values of Dropdownlists and etc.
Also i need to send a file too.
I have tried the following code and it works fine:
$(".popup-content input:text,.popup-content textarea").each(function () { // Fill object by inputs
objInputs[$(this).attr("name")] = $(this).val();
});
$.ajax({ //Post information
type: "POST",
url: "myAjax.aspx",
data: { func: "Create", information: JSON.stringify(objInputs) /* Convert object to JSON string */ },
success: function (data) { // if sending was successful try to send file
var files = $("#fileImage").get(0).files; //get files form uploadfile
if (files.length > 0) {
var data = new FormData();
data.append(files[0].filename, files[0]);
$.ajax({ //Send file
type: "POST",
url: "Handler1.ashx",
contentType: false,
processData: false,
data: data,
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
But now i want to know if there is a way to send my file along with my JSON?
I found the solution.
The Jquery code should be changed to something like below:
<script>
$(document).ready(function () {
$(document).on("click", "#submit", function () {
var objInputs = {};
objInputs["id"] = "12";
$("#form1 input:text").each(function () { // Fill object by inputs
objInputs[$(this).attr("name")] = $(this).val();
});
var formData = new FormData();
formData.append("information", JSON.stringify(objInputs));
var files = $("#fileupload").get(0).files; //get files form uploadfile
if (files.length > 0) {
for (var i = 0; i < files.length; i++) {
//add each file to the form data and iteratively name them
formData.append("file-" + i, files[i]);
}
$.ajax({ //Send file
type: "POST",
url: "Handler1.ashx",
contentType: false,
processData: false,
data: formData,
success: function (data) {
alert(data)
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " " + thrownError);
},
});
}
});
});
</script>
And C# code to handling data which was sent (Handler1.ashx):
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0) //To handling files
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
if ((files[i].ContentLength < 500000) && (files[i].ContentType == "image/jpeg"))
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/Images/" + file.FileName);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
if (!string.IsNullOrEmpty(context.Request["information"])) //To handeling JSON
{
string JSON = context.Request["information"]; //JSON String
}
}
Related
I am sending array of object which contain upload file data and some string values to my controller using ajax but it sending failed.
I also tried with formdata but no luck.I want to know how i send data to controller.
Jquery/View Code:
function SaveBrandDetail() {
debugger;
var data = new Array();
var tablecount = 0;
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"fileUpload": $(this).find(".fileUploadData").get(0).files[0]
};
data.push(row);
});
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify(data),
success: function (msg) {
},
error: function () {
}
});
}
Controller File:
public ActionResult SaveData(List<Data> data)
{
bool saved = false;
}
i expect to recieve data with upload file in my controller.i have declared HttpPostedFileBase in my modal class.
var formData = new FormData();
$(".DataRow").each(function () {
tablecount = tablecount + 1;
var row = {
"SaleStartDateString": $(this).find(".clsSaleStartDateForVal").val(),
"BrandDetailId": $(this).find(".clsBrandDetailId").val(),
"SaleExpiryDateString": $(this).find(".clsSaleEndDateForVal").val(),
"BrandId": $(this).find(".clsBrandId").val(),
"Amount": $(this).find(".clsAmount").val(),
"CategoryId": $(this).find(".clsSubCategoryId").val(),
"ParentCategoryId": $(this).find(".clsParentCategoryId").val(),
"FileName": $(this).find(".fileUploadData").get(0).files[0].name
};
var file = $(this).find(".fileUploadData").get(0).files[0];
formData.append(file.name, file);
data.push(row);
});
formData.append("data", JSON.stringify(data));
$.ajax({
url: '#Url.Action("SaveData","Data")',
type: "POST",
dataType: 'json',
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
},
error: function () {
}
});
public ActionResult SaveData(string data)
{
var files = Request.Files;
List<Data> d = JsonConvert.Deserialize<List<Data>>(data);
foreach(var item in d)
{
var file = files[item.FileName];
}
bool saved = false;
}
Currently I am using JQuery AJAX and connect it to the Generic Handler (.ashx), inside the Generic Handler, I am doing the template for the Excel File that is going to save the computer (prompt save). i can achieve that while using the .aspx.cs , the reason I am doing from Generic Handler (.ashx), is because I don't know any way to hide the loading overlay after the dialog box for us to save to the computer is appear. (means the loading overlay just stick there). $(element).show() or $(element).hide() is to show or hide the loading overlay.
I am using EPPlus Library to generate the template for Excel File, however I don't know how to pass the object into client side and then prompt to save, it keeps gives me an error.
The problem I was encountered while using the Generic Handler is always gives me the parsererror message.
Here is the code that I am using:
JQuery AJAX:
var loading = $("#loading");
$("#template").click(function () {
loading.show();
$.ajax({
type: "POST",
url: "TemplateService.ashx?Month=" + $("#Month").val() + "&Year=" + $("#Year").val(),
data: {},
contentType: "application/json",
dataType: "json",
success: function (data) {
loading.hide();
console.log(data);
alert("Success");
},
error: function (xhr, text) {
loading.hide();
console.log(JSON.stringify(xhr.responseText));
console.log(JSON.stringify(text));
alert("There is a problem while processing your request");
}
});
});
Generic Handler (.ashx):
public class TemplateService : IHttpHandler, IRequiresSessionState
{
private int Month = 0;
private int Year = 0;
public void ProcessRequest(HttpContext context)
{
Month = Convert.ToInt32(context.Request.Params["Month"]);
Year = Convert.ToInt32(context.Request.Params["Year"]);
try
{
string MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Month);
string fileName = string.Format("{0} - {1} {2}.xlsx", "Excel Template", MonthName, Year);
using (var package = new ExcelPackage())
{
package.Export();
using (var stream = new MemoryStream())
{
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
package.SaveAs(stream);
stream.WriteTo(context.Response.OutputStream);
context.Response.Write(stream);
}
}
}
catch (Exception)
{
ProcessResponse(context, Response());
}
}
private string Response(bool isSuccess = false)
{
string status = (isSuccess) ? Constant.SUCCESS : Constant.FAILED;
return JsonConvert.SerializeObject(new
{
Status = status
});
}
private void ProcessResponse(HttpContext context, string response)
{
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Export function:
public void Export(this ExcelPackage package)
{
try
{
package.Workbook.Worksheets.Add("Excel Template");
var workSheet = package.Workbook.Worksheets["Excel Template"];
var columnNames = new string[]
{
"First Column",
"Second Column",
"Third Column"
};
var headerRow = new List<string[]>()
{
columnNames
};
var cells = workSheet.Cells[1, 1, 1, 3];
cells.LoadFromArrays(headerRow);
cells.AutoFilter = true;
cells.AutoFitColumns();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
HTML:
<form>
<asp:Button ID="Submission" runat="server" OnClick="Submission_Click" Text="Upload" />
<input type="button" id="Template" value="Template" />
</form>
<script type="text/javascript">
var loading = $("#loading");
$("form").submit(function () {
loading.show();
});
$("#template").click(function () {
loading.show();
$.ajax({
type: "POST",
url: "TemplateService.ashx?Month=" + $("#Month").val() + "&Year=" + $("#Year").val(),
data: {},
contentType: "application/json",
dataType: "json",
success: function (data) {
loading.hide();
console.log(data);
alert("Success");
},
error: function (xhr, text) {
loading.hide();
console.log(JSON.stringify(xhr.responseText));
console.log(JSON.stringify(text));
alert("There is a problem while processing your request");
}
});
});
</script>
Your answer much appreciated.
Thank you.
I am working with the Bing Maps v8 API, trying to load my own GeoJSON onto a Bing Maps as in this example: https://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#geoJsonReadObject+JS
I am creating my JSON successfully (I have tested it using the Bing Maps Drag and Drop feature and all of my points show on the map. https://bingmapsv8samples.azurewebsites.net/#GeoJson%20Drag%20and%20Drop.
I am trying to get my GeoJSON to automatically load on a map, and I am receiving a JSON failure, and I am not sure why. (I am rather new to GeoJSON/JSON.)
Javascript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
var featureCollection = Microsoft.Maps.GeoJson.read(getGeoJson(), { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
function getGeoJson() {
$(function (callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
});
}
}
Controller:
[HttpPost]
public JsonResult PatGeoJSON(string parent)
{
JObject jsondata = JObject.FromObject(new
{
type = "FeatureCollection",
features = from p in pList
select new
{
type = "Feature",
geometry = new Geometry
{
type = "Point",
coordinates = new double?[] { p.GeoLocation.Longitude, p.GeoLocation.Latitude }
},
properties = new Properties
{
MemberName = p.MemberName,
/// etc...
}
}
});
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
My result is currently a "Failure" alert with the JSON string. Note: if I hardcode my GeoJSON as the result from the getGEOJSON function, all of my points show up on the map. Am I not reading the JsonResult correctly in my script?
Your getGeoJson function is asynchronous, so it doesn't return anything, this bing maps is receiving a null value to parse which it simply ignores and this no error. Specify a callback function when loading your geojson and when it responds, then read its value. Here is an updated version of your JavaScript:
function loadMapScenario() {
var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
credentials: 'KEY',
center: new Microsoft.Maps.Location(32.560116, -117.057889),
zoom: 5
});
Microsoft.Maps.loadModule('Microsoft.Maps.GeoJson', function () {
getGeoJson(function(data){
var featureCollection = Microsoft.Maps.GeoJson.read(data, { polygonOptions: { fillColor: 'rgba(0, 255, 255, 0.3)' } });
for (var i = 0; i < featureCollection.length; i++) {
map.entities.push(featureCollection[i]);
}
});
});
function getGeoJson(callback) {
var data;
$.ajax({
type: "POST",
url: "/TD/PatGeoJSON",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.responseText.data)
data = response.RepsonseText;
callback(data)
},
failure: function (response) {
alert("Failure: " + response.responseText);
},
error: function (response) {
alert("Failure: " + response.responseText);
}
});
}
}
This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
I need to upload a file to the server and send a GUID value, both needed to complete an operation.
Is it possible to send both with one $.ajax statement?
Here's a snippet of the Upload action method I'm using
[HttpPost]
public ActionResult Upload()
{
HttpPostedFileBase file = Request.Files[0];
}
and here's a snippet of the Javascript code I'm using to send the file to the server
function upload() {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
}
$.ajax({
type: 'post',
url: '/myController/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
}
This code is working well. The file is uploaded as expected but now I need to send a GUID to the same controller (Upload) so I wonder if I can send the GUID with the file in the same $.ajax statement?
function upload() {
var formData = new FormData();
var totalFiles = document.getElementById("FileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("FileUpload").files[i];
formData.append("FileUpload", file);
formData.append("guid", theGuid);
}
$.ajax({
type: 'post',
url: '/myController/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
}
on server side:
Request.Form["guid"];
Request.Files["FileUpload"];
i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});