代码之家  ›  专栏  ›  技术社区  ›  user171910

Net MVC如何在视图中显示模型的图像属性?

  •  6
  • user171910  · 技术社区  · 17 年前

    我是asp.NETMVC新手,但我正在尝试用GDI+做一个有趣的应用程序,我需要用asp.NETMVC做一些图像查看。

    namespace DomainModel.Entities
    {
        public class BackgroundImage
        {
            // Properties
            public Image Image {get; private set; }
    
            public BackgroundImage()
            {
                Image = Image.FromFile(@"D:\ProjectZero\DomainModel\image\bkg.PNG");
    
            }
        }
    }
    

    控制器向视图发送以下信息:

    public ActionResult Index()
            {
    
                BackgroundImage bkImg = new BackgroundImage(); 
                return View(bkImg);
            }
    

    视图如下所示:

    <p> Height: </p><%= Model.Image.Height //it prints the height of the image %> </br>
    <p> Width: </p><%= Model.Image.Width //it prints the width %> </br>
    <p> Image: </p><%= Model.Image //does not work to display the image %>
    

    如何显示该图像属性?

    有没有我错过的Html助手?

    谢谢你抽出时间!

    2 回复  |  直到 13 年前
        1
  •  16
  •   Darin Dimitrov    17 年前

    您需要编写一个控制器操作,将图像写入响应流,并将适当的内容类型设置为“image/png”。然后你可以使用 img 标记以在视图中引用此操作:

    public ActionResult Image()
    {
        byte[] image = GenerateImage();
        return File(image, "image/png");
    }
    

    <img src="<%= Url.Action("Image") %>" alt="" />