Display Image using AJAX - ajax

I am trying to display a picture that I am calling from the controller using AJAX, this is my code:
<div id="productImg" style="display:none;">
</div>
<script>
function showPic(id) {
$.ajax({
type: "GET",
url: "/Equipment/GetImage",
data: { 'productId': id },
success: function (data) {
$("#productImg").html(data)
}
});
</script>
And the method on my controller looks like this:
public virtual FileContentResult GetImage(int productId) {
Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
What I am getting is a lot of code and not the image. What else could I try?

You don't need to use AJAX for this. Images are separate resources for a page and are loaded as separate requests already. Just link to it:
<div id="productImg">
<img src="/Equipment/GetImage?productId=123" alt="Product" />
</div>
For making that happen dynamically in JavaScript, all you need to do is change that src value:
function showPic(id) {
$('#productImg img').src = '/Equipment/GetImage?productId=' + id;
}
As an aside, the reason your approach doesn't work is because what you're getting back from the server isn't HTML, it's the raw image data. The HTML to display an image is not the image data itself, it's just an img tag with a URL. (That URL can contain an encoded copy of the actual data, but it really doesn't need to in this case.)

Please modify your Action method to something like this:
public virtual ActionResult GetImage(int productId)
{
Product prod = _db.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null)
{
return new FileStreamResult(prod.ImageData, prod.ImageMimeType);
}
else
{
return null;
}
}
Let me know if this works...
Alternatively, what you can do is, you can prepend some text to the image data coming from the ajax call to display the image. All you have to do is, just prepend
data:image/png;base64,
where image/png is the mime-type.
Then when you push your src to the image tag the src will look something like this...
<img src="data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP
C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA
AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J
REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq
ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0
vr4MkhoXe0rZigAAAABJRU5ErkJggg==" />
Hope it works...

Related

What to return after Ajax call asp.net

After ajax call is completed and the model is posted successfully to the controller, what should the controller return?
In my case, I just want to add an item to the wishlist and that's it, no redirect.
Controller can return a message or somethingelse for sure that your action did successful
This question you need to know two points, 1.What type can asp.net core return? 2.What type can ajax can receive.
First, Asp.net core can return the following types: Specific type, IActionResult, ActionResult<T>, Learn more details in this document.
Second, Ajax can send and receive information in various formats, including JSON, XML, HTML, and text files.
From your question, I think you want to recive the model from controller and add it to the wishlist in the view. So, In my opinion, You can directly return the specified model, Asp.net core will serialize models to Json Automatically. Then you can use it in your ajax success method.
simple demo:
<div class="text-center" id="Test">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
<button onclick="GetDetails(2)">submit</button>
#section Scripts{
<script>
function GetDetails(id){
var postData = {
'ProductId': id,
};
$.ajax({
type: "Post",
url: "/Home/privacy",
data: postData,
success: function (res) {
document.getElementById("Test").innerHTML = res["name"];
}
});
}
</script>
}
Controller
List<Student> students = new List<Student>()
{
new Student()
{
Id="1",
Name="Jack",
Country="USA"
},
new Student()
{
Id="2",
Name="Nacy",
Country="Uk"
},
new Student()
{
Id="3",
Name="Lily",
Country="Cn"
}
};
[HttpPost]
public Student Privacy(string ProductId)
{
var result = students.Where(x => x.Id == ProductId).FirstOrDefault();
return result;
}

Using $.ajax to send data via HttpPost in aspnet5, is not working

Ok basically I have a column, and when you click the header a couple of input tags appear dynamically, to change column name and submit it. I want to change it and show it right away using ajax. The code to do this is below, and sorry but the code is in coffee script. Also I am using ASPNET5 RC1 with MVC6.
SumbitColumnForm = () ->
$('.panel-heading').on 'click', 'input.ColumnTitleSumbit', (event) ->
event.preventDefault();
columnName = $('.NewColumnName').val().trim()
columnNumber = $(this).parent().parent().attr 'id'
newColumnData = "{
'ColumnName': 'columnName'
'ColumnNumber': 'columnNumber'
}"
$.ajax
url: '/Board/ChangeColumnName',
type: 'POST'
dataType: 'json',
data: newColumnData,
success: (data) ->
#res = $.parseJSON(data);
alert "Hit the Success part";
error: (xhr, err) ->
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
The controller actions are
[Route("{p_BoardName}")]
public IActionResult Show(string p_BoardName)
{
m_Board.BoardName = p_BoardName;
ViewData["BoardName"] = m_Board.BoardName;
return View(m_Board);
}
[HttpPost]
public IActionResult ChangeColumnName(ColumnModel newColumnData)
{
string name = newColumnData.ColumnName;
m_Board.ColumnList[newColumnData.ColumnNumber].ColumnName = name;
return View("Show", m_Board);
}
Also the modelS if needed
public class ColumnModel
{
private string m_name;
private int m_columnNumber;
public int ColumnNumber { get { return m_columnNumber; } }
public string ColumnName { get { return m_name;} set { m_name = value; } }
public ColumnModel(string p_Name, int p_ColumnNumber)
{
m_name = p_Name;
m_columnNumber = p_ColumnNumber;
}
}
public class BoardModel
{
private string m_BoardName;
private List<ColumnModel> m_ColumnList;
[Required]
public string BoardName { get { return m_BoardName; } set { m_BoardName = value; } }
public List<ColumnModel> ColumnList
{
get { return m_ColumnList; }
set { m_ColumnList = value; }
}
}
So I have debugged both the Javascript and the controller action ChangeColumnName, and it is not hitting it. The javascript also does not hit the success part of the ajax call also. I have tried everything that comes to mind and done a lot of googling but it just won't work. I feel like it is because of the way I am sending the data for the $.ajax call but really I just don't know why this doesn't work.
Also if i want to update the column name, by removing the input and adding the normal HTML to display the name, am I right to return a view in the action method ChangeColumnName? I mean will it reload the page or add it dynamically. Will I have to add JS code in the success attribute of the $.ajax call to change it dynamically?
Any help will be greatly appreciated. Thank you.
Edit: Added the board model
Edit2: Updating showing the html code as a request of Stephen.
Using bootstrap column/grid design, and also bootstrap panels. I basically have column shown by html
<div id="1" class="panel panel-default BoardColumn">
<div class="panel-heading">
<h3 class="panel-title">Something1</h3>
</div>
</div>
I want to change the header class 'panel-title' and update it dynamically without reloading the page. I have set up another ajax call, so when the header is clicked a few input tags are added and and the html is changed to the following. In minimal explaining I have done this using jquery append and remove functions.
<div id="1" class="panel panel-default BoardColumn">
<div class="panel-heading">
<input class="PreviousColumnName" type="hidden" style="display: none;" value="Something1">
<input class="NewColumnName" name="ColumnName">
<input class="ColumnTitleSumbit" type="submit" value="Continue">
</div>
</div>
Now I want to get the value of the input with class name 'NewcolumnName', update the current column name in the model and place its new name. When the submit button is clicked, I want to remove the input tags and go back to the original html before that, showings it new column name without reloading.

Kendo UI ListView Template in MVC4

I am trying to get image files from the database and bind it to a KendoUI ListView. The problem is that it is not showing images at all.
This is what I have done:
View
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<img src="#Url.Content("#:PhotoID# + #:MIMEType#")" />
</div>
</script>
<div id="imageListView2" class="demo-section">
#(Html.Kendo().ListView<WorcesterMarble.ViewModels.PhotosViewModel>()
.Name("listView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("GetImages", "StockReceiptsGrid").Data("passStockIDToListView"));
dataSource.PageSize(1);
})
.Pageable()
.Selectable(selectable => selectable.Mode(ListViewSelectionMode.Multiple))
//.Events(events => events.Change("onChange").DataBound("onDataBound"))
)
</div>
Controller
public JsonResult GetImages([DataSourceRequest] DataSourceRequest request, int stockReceiptID)
{
var photos = _stockPhotosRepository.GetStocReceiptkPhotos(stockReceiptID).ToList();
var photosList = new List<PhotosViewModel>();
//var photosList = new List<FileContentResult>();
if (photos.Count != 0)
{
foreach (var stockPhoto in photos)
{
var photoVm = new PhotosViewModel();
photoVm.PhotoID = stockPhoto.PhotoID;
photoVm.Image = stockPhoto.ImageData;
photoVm.MIMEType = stockPhoto.MIMEType;
// FileContentResult file = File(stockPhoto.ImageData, stockPhoto.MIMEType);
photosList.Add(photoVm);
}
return Json(photosList.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
return null;
//FilePathResult file = this.File("/Content/Images/80.jpeg", "image/jpeg");
//return file;
}
return null;
}
Photo View Model:
public class PhotosViewModel
{
public int PhotoID { get; set; }
public byte[] Image { get; set; }
public string MIMEType { get; set; }
public int StockReceiptID { get; set; }
}
I am not sure if the problem is caused by the image url setting in the template. as you see it is not actually a url because the image is not saved anywhere except from the database. this is a screenshot of how the listview looks like; simply blank even though there must 15 images displayed!
Please let me know any clues or solutions to this problem.
I know this is a bit older, but what you need to do is change the line return Json(photosList.ToList(), JsonRequestBehavior.AllowGet); to the following:
return Json(photosList.ToDataSourceResult(request),
JsonRequestBehavior.AllowGet);
If the method ToDataSourceResult is not recognized, you have to add
using Kendo.Mvc.Extensions;
on top of your document.
It looks like you're missing a return in your controller (just before the end of your if)
return Json(photosList.ToList(), JsonRequestBehavior.AllowGet);
EDIT
Also, I noticed this:
<img src="#Url.Content("#:PhotoID# + #:MIMEType#")" />
Shouldn't that be:
<img src="#Url.Content("#:ImageData#")" />
or something similar?
It might be to late to answer, but your issue is that the json data being sent back to your view is to large so your images are not showing, rather save your images to a file and then render your images via a URL.

Dynamically load Partial Views

How can i dynamically load a Partial View?
I mean I have this view, lets say ListProducts, there I select some dropdownlists with products, etc, and with the selected values from those I wanna fill a partial view, which would be in a div that was invisible but after onchange() event would become visible and with the data from the specific selected items.
Use jQuery's $.load() with a controller action that returns a partial view.
For example:
HTML
<script type="text/javascript">
$(document).ready(function()
{
$("#yourselect").onchange(function()
{
// Home is your controller, Index is your action name
$("#yourdiv").load("#Url.Action("Index","Home")", { 'id' : '123' },
function (response, status, xhr)
{
if (status == "error")
{
alert("An error occurred while loading the results.");
}
});
});
});
</script>
<div id="yourdiv">
</div>
Controller
public virtual ActionResult Index(string id)
{
var myModel = GetSomeData();
return Partial(myModel);
}
View
#model IEnumerable<YourObjects>
#if (Model == null || Model.Count() == 0)
{
<p>No results found</p>
}
else
{
<ul>
#foreach (YourObjects myobject in Model)
{
<li>#myObject.Name</li>
}
</ul>
}
You can do this by following these steps. In your controller, you return a partial view.
[HttpGet]
public virtual ActionResult LoadPartialViewDynamically()
{
var query = _repository.GetQuery();
return PartialView("_PartialViewName", query);
}
then in the view you have an empty div
<div id="partialgoeshere"></div>
and then load the partial view using jQuery:
function LoadPartialView() {
$.get("#Url.Action(MVC.ControllerName.LoadPartialViewDynamically())", { null }, function (data) {
$("#partialgoeshere").empty();
$("#partialgoeshere").html(data);
});
}
Hope this helps
I believe you can do something like this example, just using the change event on your dropdown instead. It's a simple jQuery call, you can find more on the jQuery website.
$("#dropdown").change(function() {
$("#destination").load("/Products/GetProduct", $(this).val(),
function(result) {
// do what you need to do
});
});
The first parameter is the view you need to call for the details.
The second parameter is the selected value.
The third parameter of the $.load function is the callback function, where you can parse the result and do what you need to do.
If you have a multiple select $(this).val() that will give you an array with the selected options.
If you want only return a Json object you may want to follow this example.
Use Ajax :)
http://api.jquery.com/jQuery.ajax/
Example:
$.post(window.gRootPath + "Customer/PartialView", { Question: questionId})
.done(function (data) {
$('#partialDiv').html(data.responceText);
});
You can use ajax to call action an then just insert html string using jQuery to the page where you want it to appear:
Server-side:
Render partial view to string
Renders partial view on server to html string, useful when you need to add partial view to ASP.NET MVC page via AJAX.
Client-side:
$('#yourDdl').change(function()
{
$.get('/InsertPartialViewUsingAjax', function (data)
{
$('#container').html(data);
});
});
The following article tells you how to do it with minimum javascript. Basically you return html instead of JSON to your response object.
https://www.simple-talk.com/content/article.aspx?article=2118

Mvc 3 Image Upload Gallery

I have implemented a file upload for images using ASP.NET Mvc 3 and the Microsoft.Web.Helpers NuGet package. The implementation is quit simple as it allows you to browse for a file and upload it to a specified directory.
Here is what I have for my image upload solution using ASP.NET MVC 3 and the Microsoft.Web.Helpers NuGet plugin.
Now the ViewModel code
namespace MvcImageUpload.Models {
public class ImageUploadViewModel {
[UIHint("UploadedImage")]
public string ImageUrl { get; set; }
public string ImageAltText { get; set; }
}
}
Now for the controller I've simply dropped this into the Home controller, since this is just a mock project to get it working. I just added an ActionResult which takes an ImageUploadViewModel as a parameter.
public ActionResult Upload(ImageUploadViewModel model) {
var image = WebImage.GetImageFromRequest();
if (image != null) {
if (image.Width > 500) {
image.Resize(500, ((500 * image.Height) / image.Width));
}
var filename = Path.GetFileName(image.FileName);
image.Save(Path.Combine("../Uploads/Images", filename));
filename = Path.Combine("~/Uploads/Images", filename);
model.ImageUrl = Url.Content(filename);
model.ImageAltText = image.FileName.Substring(0, image.FileName.Length - 4);
}
return View("Index", model);
}
My view for the uploading of images is simple, it has an Html.BeginForm, which handles the Post form method and has the encoding type set to be "multipart/form-data".
Then using The Microsoft.Web.Helpers.FileUpload helper, I request an image from the HTTP post and then display it using a custom DisplayFor template, called ImageViewer.
#model MvcImageUpload.Models.ImageUploadViewModel
#using Microsoft.Web.Helpers;
#{
ViewBag.Title = "Index";
}
<h2>Image Uploader</h2>
#using (Html.BeginForm("Upload", "Home", FormMethod.Post,
new { #encType = "multipart/form-data" })) {
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false,
includeFormTag: false, addText: "Add Files", uploadText: "Upload File") <br />
<input type="submit" name="submit"
value="Upload Image" text="Upload Images"
style="font-size: .9em;" />
#Html.DisplayFor(x => x, "ImageViewer")<br />
}
Here is what the custom DisplayTemplate looks like
#model MvcImageUpload.Models.ImageUploadViewModel
#if (Model != null) {
<h4 style="color:Green;">Upload Success!</h4>
<p>
Alt Text has been set to <strong>#Model.ImageAltText</strong>
</p>
<img style="padding: 20px;"
src="#(String.IsNullOrEmpty(Model.ImageUrl) ? "" : Model.ImageUrl)"
id="uploadedImage" alt="#Model.ImageAltText"/>
}
This all works and the image gets successfully uploaded to the /Uploads/Images/FileName.extension on the form post.
My question
How can I now have another view to display all the images in that directory, paged and be able to select and delete and image, from the view and the directory?
Also I know the Microsoft.Web.Helpers.FileUpload, supports uploading of multiple files, but I can't find how to implement this with my current solution. Any help would be greatly appriceated.
After you click the Upload Image button, the system should call method which uses Request to get the file.
[HttpPost]
public ActionResult Upload()
{
if(Request.Files != null && Request.Files.Count > 0)
{
for (int i = 0; i < request.Files.Count; i++)
{
var postFile = request.Files[i];
if (postFile != null && postFile.ContentLength > 0)
{
if (postFile.ContentLength < GetMaxRequestLength()) //10MB
{
var file = new ContractAttachment
{
Name = Path.GetFileName(postFile.FileName),
ContentType = postFile.ContentType,
FileLength = postFile.ContentLength,
FileData = GetStreamBuffer(postFile)
};
files.Add(file);
}
}
}
}
}
Hope this help.
what you are asking about looks rather implementation to me then any query....
to Display:
Fetch all images from your Uploads/Images directory through DirectoryInfo... you can search a directory based on some extension and then it will give you a result set which you can iterate.....
Create a view that will display all records as Image links and in controller fetch the resultset to that View.... Bind those records as you want them to display in your VIEW...
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo("your directory path");
var filesinfo= info.GetFiles("*.jpg", System.IO.SearchOption.AllDirectories);
var filenum= filesinfo.GetEnumerator();
while (filenum.MoveNext())
{
//populate some entity like in your case you have ImageUploadViewModel
}
and you can implement you delete logic using Ajax or through post back depends how you want it....
Asp.net MVC Views following this tutorial and it will let you go through this....
but again what you are asking is more like implementation Code not any issue....
The approach I've followed previously, is to persist the file information in a database(or whatever is appropriate). e.g. path, filename, content-type, filesize.
This gives you the most flexibility when editing (alt text, title, description, relation to other objects).
Downloading/Viewing the files can then be handled based on path convention, by creating a ViewImage controller which just gets an image id as parameter.
You can then build a url from the path to the file and you only need to set the content-type.
IIS then does the rest.

Resources