开发者

How to populate image in asp.net MVC 2

I am saving the user image in application domai开发者_Python百科n file system. and the storing path in a database. I am getting the path in my User.PhotoPath property. I want to show the image on the page of this photopath . How do I show it?

I am using Asp.net MVC 2 + C#.


Provide the PhotoPath as a property on your viewmodel:

public class UserViewModel
{
    //...
    public string PhotoPath { get; set; }
}

Controller:

public ActionResult Show(int id) 
{
    // load User entity from repository
    var viewModel = new UserViewModel();
    // populate viewModel from User entity
    return View(viewModel);
}

View:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<UserViewModel>" %>

...
<img src="<%= Model.PhotoPath %>" alt="User Photo" />
...

You could also pass the User entity directly to the view, but it's not recommended to do that. But if you want to do it this way, then you have to change the view's page directive accordingly:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<User>" %>


Set the User as Model for the view, and the use the PhotopPath as source for the image element.

<img src="<%= model.PhotoPath %>" alt="whatever you want" />

Alternatively you can store the path within the controller in your ViewData, if you want to use another class as model for the view like this:

Controller:

ViewData["PhotoPath"] = yourUser.Photopath;

View:

<img src="<%= ViewData["PhotoPath"].ToString() %>" alt="whatever you want" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜