How can get image with Jquery Ajax - asp.net-mvc

I can can get picture by Razor '#Action' but with Ajax Can't. I write
in controller:
public ActionResult getCommodityPic()
{
var f= File(Server.MapPath("~/App_Data/CommodityPics/eee/1") + ".jpg", "image/jpg");
return f;
}
and in java script :
$(document).ready(function () {
ShowCommodities();
getCommodityPic();
});
function getCommodityPic() {
$.ajax({
url: '#Url.action("getCommodityPic")',
type: 'Get',
dataType: 'image/jpg',
success: function (Data, Status, jqXHR) {
$('#img1').attr('src', Data);
}
});

$.ajax({
url: '#Url.Action("DownloadPic", "MyController")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: {
id: Id
},
type: "GET",
success: function (Data, Status, jqXHR) {
if (Data != "") {
alert("Empty");
return;
}
window.location ='#Url.Action("DonloadPic","Mycontroller")';
}
});
in Controller:
public ActionResult DownloadPic(int? id)
{
Lesson l = new Lesson();
l = db.Lesson.Single(p => p.id == id);
if (l.picture == null)
{
string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/Image/book-03.jpg");
byte[] img = System.IO.File.ReadAllBytes(targetFolder);
return File(img, "image/jpg");
}
return File(l.picture, "image/jpg");
}

If you want to display the image dynamically, then try this. You may not need an Ajax call for this.
$('#img1').html('<img src="getCommodityPic" />')
If you want to process the image (read its raw binary) then this answer should help - https://stackoverflow.com/a/20048852/6352160

Related

Unable to send array data using ajax with ASP.NET Core and Entity Framework Core

I am trying to send array to the controller but it's blank in the controller parameter.
Ajax function is:
$('#pending').click(function () {
SaveTestResult("/Reception/PatientTests/SavePendingTest");
});
function SaveTestResult(url) {
var pid = $('.patientId').attr('id');
var tid = "";
var tval = "";
var tpid = "";
var tests = [];
$("table > tbody > tr").each(function () {
testId = $(this).find('.tid').val();
if (typeof (testId) != "undefined") {
tid = testId;
}
var rowText = ""
$(this).find('td').each(function () {
tpid = $(this).find('.tpId').val();
tval = $(this).find('.result').val();
if (typeof (tpid) != "undefined") {
tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
}
});
});
// alert(JSON.stringify(tests));
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(tests),
contentType: "application/json",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
}
This is the controller method:
[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
if (ModelState.IsValid)
{
foreach (PendingTestResult ptr in pendingTestResult)
{
_db.Add(ptr);
await _db.SaveChangesAsync();
}
// return new JsonResult("Index");
}
return new JsonResult(pendingTestResult); ;
}
But when run the code I see data array filled but inside of the SavePendingTest action, pendingTestResult is empty and not filled! I also tried the [FromBody] tag inside action params, but it does not work either!
Help me resolve this
you are sending a string with no names so the controller can not get the values.
change you code to
$.ajax({
type:"POST",
url:url,
data:test
...
});
the test should be an object not a string.
You can pass the list of objects by :
$.ajax({
type: "POST",
url: "Reception/PatientTests/SavePendingTest",
data: { pendingTestResult: tests },
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
pendingTestResult in data:{ pendingTestResult: tests } matches the parameter name on action and remove the contentType setting .

AJAX Post method not hitting controller

Can anyone point me here, what's wrong I am doing? my controller not hitting on Ajax post
Ajax Code
<script type="text/javascript">
$(document).ready(function () {
$('#btncreate').click(function () {
var projectid = $("#txtprojectid").val();
var financetype = $("#txtfinancetype").val();
var actualcost = $("#txtactualcost").val();
$.ajax({
url: 'Projects/CreateFinanceItems?pid=' + projectid + "&ft=" + financetype + "&ac=" + actualcost,
datatype: 'json',
success: function (response) {
alert("Yes");
if (response != null) {
$('#displayproContainer').load('/Projects/PartialprojectFinanceItem');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
});
});
</script>
Controller Code
[HttpPost]
public ActionResult CreateFinanceItems(string pid, string ft, string ac)
{
return View();
}
First of all , you have forget to specify the type of request in your Ajax. the default one is Get.
Second thing you have to start the url of the request with / which means the root URl of the site followed by the path of of the Action result.
<script type="text/javascript">
$(document).ready(function () {
$('#btncreate').click(function () {
var projectid = $("#txtprojectid").val();
var financetype = $("#txtfinancetype").val();
var actualcost = $("#txtactualcost").val();
$.ajax({
url: '/Projects/CreateFinanceItems?pid=' + projectid + "&ft=" + financetype + "&ac=" + actualcost,
type: 'POST',
datatype: 'json',
success: function (response) {
alert("Yes");
if (response != null) {
$('#displayproContainer').load('/Projects/PartialprojectFinanceItem');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
});
});
</script>

Excel file not saved in user's PC

I have tried to download an excel file from the server to user's PC. I have the following codes from the internet. I have modified the codes a bit....
But when I run the code, nothing happens. The save dialog box is not popping up. What I really want to happen is that the excel file from the server will be saved in user's PC by popping up a save dialog box.
Please help!!!
public void DownloadFile(string url)
{
string path = Server.MapPath("~/Images/0ca66926-6977-43d3-9c97-f84a43f6ce5d.xls");
var file = new FileInfo(path);
string Outgoingfile = "FileName.xlsx";
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
else
{
Response.Write("This file does not exist.");
}
}
$.ajax({
url: '#Url.Action("DownloadFile", "Home")',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({ url: urlLink}),
success: function(res) {
},
error: (function() {
alert("Error to retrieve selected report");
})
});
Since you are looking for a working download file code, I am sharing what we use.
We have two call process to download code. First call get the file prepared and saved on server. Second call shown below read file content and return a file object.
Controller.cs:
[HttpGet]
public ActionResult DownloadStream(string fileName, int searchId)
{
var tempStore = _searchService.GetTempStore(searchId);
var bytes = tempStore.DataAsBlob;
if (bytes != null)
{
var stream = new MemoryStream(bytes);
_searchService.DeleteTempStore(searchId);
return File(stream, "application/vnd.ms-excel", fileName);
}
_logger.Log("Export/DownloadStream request failed", LogCategory.Error);
return Json("Failed");
}
View.cshtml
Following line calls DownloadStream method on server, server send a file object that gets save on user machine.
window.location = '/Export/DownloadStream?fileName=' +
result+"&searchId="+searchId;
function ExportData(exportType, exportFormat) {
var searchId = document.getElementById('hfSelectedDriverId').value;
var model = { searchId: searchId, exportType: exportType, exportFormat: exportFormat };
$.ajax({
url: '#Url.Action("ExportDriverFile", "Export")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function (result) {
result = result.toString().replace(/"/gi, "");
if (result == "" || result == "failed")
{
alert("File download failed. Please try again!");
}
else
{
window.location = '/Export/DownloadStream?fileName=' + result+"&searchId="+searchId;
}
})
.error(function (xhr, status) {
//alert(status);
});
}

MVC: pass parameter to action using Jquery.ajax()

I'm pretty new to MVC. I need to make ajax call to an Action with parameters using html.Action(). I'm unable to pass this..
Hope it will be helpful for other MVC begineers as well..
HTML:
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{#onclick=string.Format("return checkFleetAddedandScroing()")}) %>
Jquery:
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Action:
public JsonResult CheckFleetExists(Guid fleetId )
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(exists, JsonRequestBehavior.AllowGet);
}
I need to pass fleetid to action which is in Model.SelectedFleet.ID. Its being used somewhere on pages. But i'm unable to use that somehow..
please suggest where i'm doing wrong...
It looks like you are trying to invoke a controller action using AJAX when the link is clicked and depending on the result of this call either allow the user to be redirected to the actual AddRace action or be prompted with an error message.
The problem with your code is that you are attempting to return true/false from within the success AJAX callback which doesn't make any sense. You need to always return false from the click callback and inside the success callback, depending on the returned value from the server, redirect manually using the window.location.href function.
HTML:
<%: Html.ActionLink(
"Add Race",
"AddRace",
new {
eventId = Model.EventId,
fleetId = Model.SelectedFleet.ID
},
new {
data_fleetid = Model.SelectedFleet.ID,
#class = "addRace"
}
) %>
Jquery:
<script type="text/javascript">
$(function () {
$('.addRace').click(function (evt) {
$.ajax({
type: 'GET',
url: '<%= Url.Action("CheckFleetExists") %>',
cache: false,
data: { fleetId: $(this).data('fleetid') },
success: function (data) {
if (data.exists) {
// the controller action returned true => we can redirect
// to the original url:
window.location.href = url;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
</script>
Action:
public ActionResult CheckFleetExists(Guid fleetId)
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
Remark: inside your AddRace controller action don't forget to perform the same verification as you are doing inside your CheckFleetExists. The user could simply disable javascript and the AJAX call will never be done.
change your action like this :
public JsonResult CheckFleetExists(string fleetId)
{
var fleetGuid = Guid.Parse(fleetId);
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetGuid );
}
catch
{
}
return new JsonResult{ Data = exists};
}
and change you ActionLink so :
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{onclick=string.Format("return checkFleetAddedandScroing({0})",Model.SelectedFleet.ID)}) %>
and your script block may look something like this :
function checkFleetAddedandScroing($fleetId) {
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
data : { "fleetId" : $fleetId },
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Problem was in answers that url to action was not complete..i did it using this way
function checkFleetAddedandScroing() {
// debugger;
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}

MVC serialize object, list of objects, collections in Json

Parsing json returned from the controller. For some reason when returning a dictionary I need to do "ToString()" on the key element, otherwise I get an error. Why?. Are the samples below the correct way/best way to serialize json? thanks
Controller:
// JSON
public ActionResult GizmosJsonObject()
{
var gizmo = new Gizmo
{
Id = 2343,
Name = "Some awesome name",
Quantity = 32,
IntroducedDate = DateTime.Now
};
return this.Json(gizmo);
}
public ActionResult GizmosJsonObjectCollection()
{
var gizmos = new List<Gizmo>();
gizmos.Add(new Gizmo
{
Id = 102,
Name = "some name1",
Quantity = 535,
IntroducedDate = DateTime.Now
});
gizmos.Add(new Gizmo
{
Id = 122,
Name = "some name1",
Quantity = 135,
IntroducedDate = DateTime.Now
});
gizmos.Add(new Gizmo
{
Id = 562,
Name = "some name1",
Quantity = 2,
IntroducedDate = DateTime.Now
});
return this.Json(gizmos);
}
public ActionResult GizmosJsonListInts()
{
var gizmos = new List<int>();
gizmos.Add(2);
gizmos.Add(56);
gizmos.Add(32);
return this.Json(gizmos);
}
public ActionResult GizmosJsonDictionaryInts()
{
var gizmos = new Dictionary<int, int>();
gizmos.Add(23, 123);
gizmos.Add(26, 227);
gizmos.Add(54, 94323);
return this.Json(gizmos.ToDictionary(x => x.Key.ToString(), y => y.Value));
}
public ActionResult GizmosJsonDictionaryStrings()
{
var gizmos = new Dictionary<string, string>();
gizmos.Add("key1", "value1");
gizmos.Add("Key2", "value2");
gizmos.Add("key3", "value3");
return this.Json(gizmos);
}
View:
<script type="text/javascript">
/*<![CDATA[*/
$(function () {
// json object
$("a.Object").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonObject", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
console.log(json.Id);
console.log(json.Name);
console.log(json.IntroducedDate);
// format date
var date = new Date(parseInt(json.IntroducedDate.substr(6)));
console.log(date);
}
});
});
// json object collection
$("a.ObjectCollection").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonObjectCollection", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
$(json).each(function () {
console.log(this.Id);
console.log(this.Name);
console.log(this.IntroducedDate);
// format date
var date = new Date(parseInt(this.IntroducedDate.substr(6)));
console.log(date);
});
}
});
});
// json list of ints
$("a.ListInts").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonListInts", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
$(json).each(function (i, e) {
console.log(json[i]);
});
}
});
});
// json dictionary of ints
$("a.DictionaryInts").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonDictionaryInts", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var value = json[key];
console.log(key);
console.log(value);
}
}
}
});
});
// json dictionary of strings
$("a.DictionaryStrings").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("GizmosJsonDictionaryStrings", "Home")',
contentType: 'application/json',
type: 'POST',
success: function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var value = json[key];
console.log(key);
console.log(value);
}
}
}
});
});
});
/*]]>*/
</script>
A JSON key must be of the type string. See the right sidebar here http://www.json.org/ where it states that a pair must take the form of string: value.
Just for corroboration, this document here http://www.ietf.org/rfc/rfc4627.txt states the following:
2.2. Objects
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.

Resources