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

6 asp.net-mvc model properties image

我是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");

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器向视图发送以下内容:

public ActionResult Index()
        {

            BackgroundImage bkImg = new BackgroundImage(); 
            return View(bkImg);
        }
Run Code Online (Sandbox Code Playgroud)

该视图如下所示:

<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 %>
Run Code Online (Sandbox Code Playgroud)

如何显示该图像属性?

我需要div的背景图片.我不需要调整图像大小,我只需要以正常大小显示它.

有没有我想念的Html助手?

感谢您的时间!

Dar*_*rov 15

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

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

在你的观点内:

<img src="<%= Url.Action("Image") %>" alt="" />
Run Code Online (Sandbox Code Playgroud)