【问题标题】:ASP.Net MVC How to display an image property of a model in a view?ASP.Net MVC 如何在视图中显示模型的图像属性?
【发布时间】:2009-09-11 08:03:27
【问题描述】:

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

我有一个具有图像属性的模型:

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 %>

如何显示该图像属性?

我需要该背景图片作为 div。我不需要调整图像大小,我只需要以正常大小显示它。

有没有我想念的 Html Helper?

感谢您的宝贵时间!

【问题讨论】:

    标签: asp.net-mvc image properties model


    【解决方案1】:

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

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

    在你的视野中:

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

    【讨论】:

    • 这解决了我的问题,但我需要使用它: public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);返回 ms.ToArray(); } 用于将我的图像转换为字节数组。
    • 我已经尝试了 2 天,并被引导到 HttpHelpers 的路径上,派生出的 ActionResults 称为 ImageResults 并且让我无处可去,这个解决方案第一次奏效,太棒了!!跨度>
    • 上述视图代码示例中缺少 At 符号。
    • @kroiz,这是因为这里给出的示例使用的是 WebForms 视图引擎,它没有 Razor 中的@ 登录这样的概念。在 WebForms 视图引擎中,您使用 &lt;%%&gt; 呈现服务器端代码。
    【解决方案2】:

    如果你想做这样的事情,你需要一个 HttpHandler。

    http://dotnetperls.com/ashx-handler

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      相关资源
      最近更新 更多