How to display an image using JQuery in MVC4 application?


This is MVC4 based application which has been used to display an image. This resource will be useful for jquery beginners as well as for MVC4 beginners. MVC stands for Model-View-Controller. Please make sure that file path in the src attribute must be a relative path to the website root and not the absolute path on the server.

Scenario: If certain file path is displayed to end user and after clicking on that,an image needs to be displayed then this code can be used.
Description: How it works?
In Razor view, JQuery can be added to achieve this functionality. DisplayImage is a class name. In my control also, I will use DisplayImage for class , so that once user will click on particular path, JQuery will be fired as class name matches.
Code and contents can be combined in the simplest manner by using Razor.


<script type="text/javascript">
$(document).ready(function () {
$(".DisplayImage").click(function (e) {
var obj = $(this).attr('src');
displaylayout = window.open('', 'Image', 'width=800,height=560');
if (displaylayout.document.firstChild.outerHTML.indexOf('img') > 0) {
displaylayout.close();
displaylayout = window.open('', 'Image', 'width=800,height=560');
}
displaylayout.document.write("<img src='" + obj + "' height=\"560px\" width=\"800px\"/>");
displaylayout.focus();
});
});
</script>

For control, it will be as follows:

<div id="someuniqueid">
<img src='@Model.propertyname_usedfor_image_filepath', height="90px" width="130px" alt="Image" class="DisplayImage"/>
</div>


Comments

Author: Arun Kambhammettu14 Aug 2013 Member Level: Gold   Points : 4

Hi Sarang,

This is good article for displaying images from JQuery,

JQuery is replacement for JavaScript as it is very light version. And Loading images from JQuery is not suggestible in my view,it increases chance of response time.

More over you given particular scale for displaying image in your screen,which means that size is fixed, lets say I am using a notebook with a very small screen then the image overlaps the remaining part of screen.

I am not a critic but my suggestion is provide an article which should not have any issues if one of us use it.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: