Here we
will learn that how to display image in asp.net mvc.
Step(1):- Go
to Sql Server management system and execute following script.
create database MVCVariousAttribute
use MVCVariousAttribute
Create table Student
(
Id int primary key identity,
FullName nvarchar(100),
Gender nvarchar(10),
Age int,
AdmissionDate DateTime,
EmailAddress nvarchar(100),
WinningPrize int,
PersonalWebSite nvarchar(100)
)
Insert into Student values
('Munesh Sharma', 'Male', 25, '2005-05-05
16:53:36.975', 'Munesh@gmail.com', 45000,'http://dotnet-munesh.blogspot.in/')
Insert into Student values
('Rahul Sharma', NULL, 30, '2006-06-06
17:42:25.865', 'Rahul@gmail.com', 35000,'http://dotnet-munesh.blogspot.in/')
Alter table Student Add Photo nvarchar(100), AlternateText nvarchar(100)
Update Student set Photo='~/Photos/Munesh.png',
AlternateText =
'munesh Photo' where
Id = 1
|
Step(2):- Go to Visual studio and add
a new project -> Select “Asp.Net MVC4 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 “Ado.net entity Data Model” and give the name it as “StudentDataModel”,
Then click on Add
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
Step(6) . In this
screen select your Database Tables and give Modal Name then click FINISH
Button.
When you will
click on finish button it will create Student Entity.
Step(6) . Right click on your project and add a folder with
name is “Photos” and put a image in this folder. Download the following image and paste in "Photos" folder.
Step(7). Add a partial class to this Model folder of this project with
the name of student. And put the following code to this class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;
namespace MVCDemoProject.Models
{
[MetadataType(typeof(StudentMetaData))]
public partial class Student
{
}
public class StudentMetaData
{
#region
dataType attribute
[HiddenInput(DisplayValue
= false)]
public
int Id { get;
set; }
[ReadOnly(true)]
[DataType(DataType.EmailAddress)]
public
string EmailAddress { get; set; }
[DataType(DataType.Currency)]
public
int? WinningPrize { get;
set; }
// Generate
a hyperlink
[DataType(DataType.Url)]
[UIHint("OpenInNewWindow")]
public
string PersonalWebSite { get; set; }
[DataType(DataType.Date)]
public
DateTime? AdmissionDate { get; set; }
#endregion
}
}
|
Now right click on controller and a controller with the name is “Home”
and put the following code in detail action method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDemoProject.Models;
namespace MVCDemoProject.Controllers
{
public class HomeController
: Controller
{
//
// GET:
/Home/
public
ActionResult Index()
{
return
View();
}
//
// GET:
/Home/Details/5
public ActionResult
Details(int id)
{
MVCVariousAttributeEntities
_context = new MVCVariousAttributeEntities();
Student
_studentDetail = _context.Students.Where(c => c.Id ==
id).SingleOrDefault();
return
View(_studentDetail);
}
//
// GET:
/Home/Create
public
ActionResult Create()
{
return
View();
}
//
// POST:
/Home/Create
[HttpPost]
public
ActionResult Create(FormCollection collection)
{
try
{
//
TODO: Add insert logic here
return
RedirectToAction("Index");
}
catch
{
return
View();
}
}
//
// GET:
/Home/Edit/5
public
ActionResult Edit(int
id)
{
return
View();
}
//
// POST:
/Home/Edit/5
[HttpPost]
public
ActionResult Edit(int
id, FormCollection collection)
{
try
{
//
TODO: Add update logic here
return
RedirectToAction("Index");
}
catch
{
return
View();
}
}
//
// GET:
/Home/Delete/5
public
ActionResult Delete(int id)
{
return
View();
}
//
// POST:
/Home/Delete/5
[HttpPost]
public
ActionResult Delete(int id, FormCollection
collection)
{
try
{
//
TODO: Add delete logic here
return
RedirectToAction("Index");
}
catch
{
return
View();
}
}
}
}
|
Step(8):- Next step is that add a view for detail action method so right click on this method -> add view -> Scaffold template as Detail
Step(9) 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
@model MVCDemoProject.Models.Student
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>Student</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.FullName)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.FullName)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Gender)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Gender)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Age)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Age)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.AdmissionDate)
</div>
<div class="display-field">
@Html.DisplayFor(model =>
model.AdmissionDate)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.EmailAddress)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.EmailAddress)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.WinningPrize)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.WinningPrize)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.PersonalWebSite)
</div>
<div class="display-field">
@Html.DisplayFor(model =>
model.PersonalWebSite)
</div>
<div class="display-label">
@Html.DisplayNameFor(model =>
model.Photo)
</div>
<div
class="display-field">
@Html.DisplayFor(model =>
model.Photo)
</div>
<div
class="display-label">
@Html.DisplayNameFor(model =>
model.AlternateText)
</div>
<div
class="display-field">
@Html.DisplayFor(model => model.AlternateText)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit",
"Edit", new
{ id=Model.Id }) |
@Html.ActionLink("Back
to List", "Index")
</p>
|
Replace the
above marking code with the following code
<div class="display-label">
@Html.DisplayNameFor(model => model.Photo) </div> <div class="display-field"> <img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" /> </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
|
Customize
HTML helper in asp.net mvc
We are making image tag, by passing
values of "src" and "alt" attributes. Like following
<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
@Html.Image(Model.Photo, Model.AlternateText)
|
Basically HTML helper return a string
,like for generating a text box we use following code
@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.
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.
namespace MVCDemoProject.CustomHtmlHelpers
{ public static class CustomHtmlHelpers { public static IHtmlString Image(this HtmlHelper helper, string src, string alt) { // Build <img> tag TagBuilder tb = new TagBuilder("img"); // Add "src" attribute tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src)); // Add "alt" attribute tb.Attributes.Add("alt", alt); // return MvcHtmlString. This class implements IHtmlString // interface. IHtmlStrings will not be html encoded. return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing)); } } } |
To use the custom Image() html helper in Details.cshtml view, then include the following using statement in “Details.cshtml
@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.
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="MVCDemo.CustomHtmlHelpers" /> </namespaces> </pages> <host ....../> </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.
No comments:
Post a Comment