Display Image In ASP.NET MVC

Here we will learn that to display image in ASP.NET MVC.

Step 1 - Go to SQL Server Management System and execute the following script.

  1. create database MVCVariousAttribute  
  2. use MVCVariousAttribute  
  3. Create table Student  
  4. (  
  5. Id int primary key identity,  
  6. FullName nvarchar(100),  
  7. Gender nvarchar(10),  
  8. Age int,  
  9. AdmissionDate DateTime,  
  10. EmailAddress nvarchar(100),  
  11. WinningPrize int,  
  12. PersonalWebSite nvarchar(100)  
  13. )  
  14. Insert into Student values  
  15. ('Munesh Sharma''Male', 25, '2005-05-05 16:53:36.975''[email protected]', 45000,'http://dotnet-munesh.blogspot.in/')  
  16. Insert into Student values  
  17. ('Rahul Sharma'NULL, 30, '2006-06-06 17:42:25.865''[email protected]', 35000,'http://dotnet-munesh.blogspot.in/')  
  18. Alter table Student Add Photo nvarchar(100), AlternateText nvarchar(100)  
  19. Update Student set Photo='~/Photos/Munesh.png',  
  20. AlternateText = 'munesh Photo' where Id = 1  
Step 2 - Go to Visual studio and add a new project. Select “Asp.Net MVC 4 Web Application” and give the name for this ,In my case it is “MVCDemoProject.

” -> Select a Project template as Empty and View engine is “Razor”, Then Click OK.

Step 3 - Add “EntityFramework dll” to reference folder in your project if you don’t have then install it through nugget package manager for more go this Go here.

Step 4 - Right click on Model folder and add “ADP.NET Entity Data Model” and give the name it as “StudentDataModel”, then click on Add.

StudentDataModel

Step 5 - When you will click Add button here you will see another window for “EntityData modal Wizard” from there you select “Generate From DataBase”, and Click Next.

Give the connection name and select your database then click on next,

next

Step 6 - In this screen select your Database Tables and give Modal Name, then click Finish button.

finish

When you will click on finish button it will create Student Entity.

Student

Step 7 - Right click on your project and add a folder with name “Photos” and put a image in this folder.Download the following image and paste in "Photos" folder.

folder

Step 8 - Add a partial class to this Model folder of this project with the name of student. And put the following code to this class,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.ComponentModel.DataAnnotations;  
  6. using System.ComponentModel;  
  7. using System.Web.Mvc;  
  8. namespace MVCDemoProject.Models  
  9. {  
  10. [MetadataType(typeof(StudentMetaData))]  
  11. public partial class Student  
  12. {  
  13. }  
  14. public class StudentMetaData  
  15. {  
  16. #region dataType attribute  
  17. [HiddenInput(DisplayValue = false)]  
  18. public int Id { getset; }  
  19. [ReadOnly(true)]  
  20. [DataType(DataType.EmailAddress)]  
  21. public string EmailAddress { getset; }  
  22. [DataType(DataType.Currency)]  
  23. public int? WinningPrize { getset; }  
  24. // Generate a hyperlink  
  25. [DataType(DataType.Url)]  
  26. [UIHint("OpenInNewWindow")]  
  27. public string PersonalWebSite { getset; }  
  28. [DataType(DataType.Date)]  
  29. public DateTime? AdmissionDate { getset; }  
  30. #endregion  
  31. }  
  32. }  
Now right click on controller and a controller with the name is “Home” and put the following code in detail action method.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MVCDemoProject.Models;  
  7. namespace MVCDemoProject.Controllers  
  8. {  
  9. public class HomeController : Controller  
  10. {  
  11. //  
  12. // GET: /Home/  
  13. public ActionResult Index()  
  14. {  
  15. return View();  
  16. }  
  17. //  
  18. // GET: /Home/Details/5  
  19. public ActionResult Details(int id)  
  20. {  
  21. MVCVariousAttributeEntities _context = new MVCVariousAttributeEntities();  
  22. Student _studentDetail = _context.Students.Where(c => c.Id == id).SingleOrDefault();  
  23. return View(_studentDetail);  
  24. }  
  25. //  
  26. // GET: /Home/Create  
  27. public ActionResult Create()  
  28. {  
  29. return View();  
  30. }  
  31. //  
  32. // POST: /Home/Create  
  33. [HttpPost]  
  34. public ActionResult Create(FormCollection collection)  
  35. {  
  36. try  
  37. {  
  38. // TODO: Add insert logic here  
  39. return RedirectToAction("Index");  
  40. }  
  41. catch  
  42. {  
  43. return View();  
  44. }  
  45. }  
  46. //  
  47. // GET: /Home/Edit/5  
  48. public ActionResult Edit(int id)  
  49. {  
  50. return View();  
  51. }  
  52. //  
  53. // POST: /Home/Edit/5  
  54. [HttpPost]  
  55. public ActionResult Edit(int id, FormCollection collection)  
  56. {  
  57. try  
  58. {  
  59. // TODO: Add update logic here  
  60. return RedirectToAction("Index");  
  61. }  
  62. catch  
  63. {  
  64. return View();  
  65. }  
  66. }  
  67. //  
  68. // GET: /Home/Delete/5  
  69. public ActionResult Delete(int id)  
  70. {  
  71. return View();  
  72. }  
  73. //  
  74. // POST: /Home/Delete/5  
  75. [HttpPost]  
  76. public ActionResult Delete(int id, FormCollection collection)  
  77. {  
  78. try  
  79. {  
  80. // TODO: Add delete logic here  
  81. return RedirectToAction("Index");  
  82. }  
  83. catch  
  84. {  
  85. return View();  
  86. }  
  87. }  
  88. }  
  89. }  
Step 9 - Next step is to add a view for detail action method so right click on this method -> add view -> Scaffold template as Detail,

view

Step 10 - At this position if you go to the following URL then it will not show you the image so for that we need to change in auto generate code in detail view.

http://localhost:3831/Home/Details/1

View Code is
  1. @model MVCDemoProject.Models.Student  
  2. @{  
  3. ViewBag.Title = "Details";  
  4. }  
  5. <h2>Details</h2>  
  6. <fieldset>  
  7. <legend>Student</legend>  
  8. <div class="display-label">  
  9. @Html.DisplayNameFor(model => model.FullName)  
  10. </div>  
  11. <div class="display-field">  
  12. @Html.DisplayFor(model => model.FullName)  
  13. </div>  
  14. <div class="display-label">  
  15. @Html.DisplayNameFor(model => model.Gender)  
  16. </div>  
  17. <div class="display-field">  
  18. @Html.DisplayFor(model => model.Gender)  
  19. </div>  
  20. <div class="display-label">  
  21. @Html.DisplayNameFor(model => model.Age)  
  22. </div>  
  23. <div class="display-field">  
  24. @Html.DisplayFor(model => model.Age)  
  25. </div>  
  26. <div class="display-label">  
  27. @Html.DisplayNameFor(model => model.AdmissionDate)  
  28. </div>  
  29. <div class="display-field">  
  30. @Html.DisplayFor(model => model.AdmissionDate)  
  31. </div>  
  32. <div class="display-label">  
  33. @Html.DisplayNameFor(model => model.EmailAddress)  
  34. </div>  
  35. <div class="display-field">  
  36. @Html.DisplayFor(model => model.EmailAddress)  
  37. </div>  
  38. <div class="display-label">  
  39. @Html.DisplayNameFor(model => model.WinningPrize)  
  40. </div>  
  41. <div class="display-field">  
  42. @Html.DisplayFor(model => model.WinningPrize)  
  43. </div>  
  44. <div class="display-label">  
  45. @Html.DisplayNameFor(model => model.PersonalWebSite)  
  46. </div>  
  47. <div class="display-field">  
  48. @Html.DisplayFor(model => model.PersonalWebSite)  
  49. </div>  
  50. <div class="display-label">  
  51. @Html.DisplayNameFor(model => model.Photo)  
  52. </div>  
  53. <div class="display-field">  
  54. @Html.DisplayFor(model => model.Photo)  
  55. </div>  
  56. <div class="display-label">  
  57. @Html.DisplayNameFor(model => model.AlternateText)  
  58. </div>  
  59. <div class="display-field">  
  60. @Html.DisplayFor(model => model.AlternateText)  
  61. </div>  
  62. </fieldset>  
  63. <p>  
  64. @Html.ActionLink("Edit""Edit"new { id=Model.Id }) |  
  65. @Html.ActionLink("Back to List""Index")  
  66. </p>  
Replace the above marking code with the following code,
  1. <div class="display-label">  
  2. @Html.DisplayNameFor(model => model.Photo)  
  3. </div>  
  4. <div class="display-field">  
  5. <img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" />  
  6. </div>  
We are using Url.Content() html helper method. This method resolves a url for a resource when we pass it the relative path.

Now run your application and output will be,

http://localhost:3831/Home/Details/1

output

Customize HTML helper in asp.net mvc

We are making image tag, by passing values of "src" and "alt" attributes. Like following,
  1. <img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" />  
Here if we want to create own HTML helper through that method we can pass image and alt text only using with that our view will not look complicated.MVC doesn’t have image() html helper so we can create it which accept image and alt text, like following,
  1. @Html.Image(Model.Photo, Model.AlternateText)  
Basically HTML helper return a string ,like for generating a text box we use following code,
  1. @Html.TextBox("TextBox Name")  
So, here TextBox() is an extension method defined in HtmlHelper class. In the above code, Html is the property of the View, which returns an instance of the HtmlHelper class.

Now add, Image() extension method, to HtmlHelper class. 
  1. Right click on MVCDemoProject application and add a "CustomHtmlHelpers" folder.

  2. Again Right click on "CustomHtmlHelpers" folder and add a with the name "CustomHtmlHelpers.cs".

  3. Write the following code. TagBuilder class is available in System.Web.Mvc namespace.
    1. namespace MVCDemoProject.CustomHtmlHelpers  
    2. {  
    3. public static class CustomHtmlHelpers  
    4. {  
    5. public static IHtmlString Image(this HtmlHelper helper, string src, string alt)  
    6. {  
    7. // Build <img> tag  
    8. TagBuilder tb = new TagBuilder("img");  
    9. // Add "src" attribute  
    10. tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));  
    11. // Add "alt" attribute  
    12. tb.Attributes.Add("alt", alt);  
    13. // return MvcHtmlString. This class implements IHtmlString  
    14. // interface. IHtmlStrings will not be html encoded.  
    15. return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));  
    16. }  
    17. }  
    18. }  

To use the custom Image() html helper in Details.cshtml view, then include the following using statement in “Details.cshtml,

  1. @using MVCDemo.CustomHtmlHelpers;  
As we intend to use this Image() html helper, in all our views, let's include"MVCDemo.CustomHtmlHelpers" namespace in web.config. This eliminates the need to include the namespace, in every view.
  1. <system.web.webPages.razor>  
  2. <pages pageBaseType="System.Web.Mvc.WebViewPage">  
  3. <namespaces>  
  4. <add namespace="System.Web.Mvc" />  
  5. <add namespace="System.Web.Mvc.Ajax" />  
  6. <add namespace="System.Web.Mvc.Html" />  
  7. <add namespace="System.Web.Routing" />  
  8. <add namespace="MVCDemo.CustomHtmlHelpers" />  
  9. </namespaces>  
  10. </pages>  
  11. <host ....../>  
  12. </system.web.webPages.razor>  
If you intend to use the Image() custom html helper, only with a set of views, then, include a web.config file in the specific views folder, and then specify the namespace in it.


Similar Articles