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

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

Related

How can I call an ASP.Net string function with jQuery AJAX?

I have a string function ASP.Net Webform. I want to call this function using AJAX.
That function returns a string value from database with a month index
protected string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
var dataValue = { "month": 1 };
$.ajax({
type: "POST",
url: "Homepage.aspx/BringDatas",
data: dataValue,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
complete: function (jqXHR, status) {
alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
}
});
Give it a try:
Code Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
ajax call
$.ajax({
type: 'GET',
url: 'Homepage.aspx/BringDatas',
data: '{"month": 1}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (response) {
alert("Response: " + response.d);
},
error: function (response) {
}
});
This is javascript side
<script type="text/javascript">
$(document).ready(
function () {
$("#Gonder").click(
function () {
$.ajax
({
type: "POST",
url: "Homepage.aspx/OrnekPost",
data: "{'parametre':'1234'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (output) {
alert("Response: "+ output);
}, error: function () {
alert("hata var");
}
});
});
})
</script>
Codebehind.cs code
[ScriptMethod]
[WebMethod(EnableSession = true)]
public static string OrnekPost(string parametre)
{
return parametre + " değeriyle post işlemi gerçekleştirildi.";
}

Ajax error calling web method

I am trying to set the date in a Bootstrap datetime picker based on drop down list selection change. I am using a web method (C#) to return "start date" given a "certificate ID".
I tried using "text" data type instead of "json" but keep getting "Cannot convert object of type System.String to type System.Collections.Generic.IDictionary"
I searched for this error type and could not find something that would resolve this issue.
$("#ddlCertificate").change(function () {
....
debugger
setStartDate($("#ddlCertificate").val());
});
function setStartDate(certItemID) {
var param = JSON.stringify(certItemID, null, 2);
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: param,
}).done(function (result) {debugger
$("#tbStartDate").val(result.d);
}).fail(function (jqXHR, textStatus, errorThrown) {debugger
alert(textStatus + ' - ' + errorThrown);
});
}
Web Method:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string GetCertItemStartDate(string certID)
{
int iCertItemID = int.Parse(certID);
DateTime dtStartDate = CertItem.GetCertItemStartDate(iCertItemID);
string JSONresult;
JSONresult = JsonConvert.SerializeObject(dtStartDate);
return JSONresult;
}
The problem was the way the parameter was being passed. In ajax call, I had:
data: param,
and had to change it to:
$("#ddlCertificate").change(function () {
....
var certID = "{ 'certID': '" + $('#ddlCertificate').val() + "'}";
setStartDate(certID);
});
function setStartDate(certItemID) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "../services/easg.asmx/GetCertItemStartDate",
cache: false,
data: certItemID,
}).done(function (result) {
var startDate = JSON.parse(result.d);
setStartDate(new Date(startDate));
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown);
});
}

ajax posting formdata error status 200 OK

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
}

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

AJAX TypeError: query is undefined

I'm trying to do a ajax request to my controller in C#, but it never reaches the controller - I get a type Error saying "query is undefined".
Here is my ajax script:
$(document).ready(function () {
$.ajax({
url: '/Account/GetAllGamesWithRoles',
type: 'POST',
data: {},
success: function (games) {
debugger;
Games = games;
BuildGames(games);
},
error: function() {
}
});
});
Here is my controller action:
[HttpPost]
public ActionResult GetAllGamesWithRoles()
{
var result = MockGames();
return new JsonResult{ Data = result, MaxJsonLength = Int32.MaxValue};
}
try this
$(document).ready(function () {
alert('called before ajax');
$.ajax({
url: "/Account/GetAllGamesWithRoles",
type: "POST",
data: {'test':'testcall'},
success: function (data) {
Games = data.Data;
BuildGames(Games);
},
error: function (request, textStatus, errorThrown) {
alert("Status: " + textStatus + "Error: " + errorThrown);
}
});
});
[HttpPost]
public JsonResult GetAllGamesWithRoles(string test)
{
var result = MockGames();
return Json{ Data = result, JsonRequestBehavior.AllowGet};
}

Categories