Correct way to show an image that comes from a controller

纵饮孤独 提交于 2019-12-14 04:22:07

问题


I have a controller that loads an image file:

    //
    // GET: /MyController/Image/id
    public ActionResult Image(string id)
    {
        var dir = @"C:\Temp\Images";
        var path = Path.Combine(dir, id + ".png");
        return File(path, "image/png");
    }

In a separate view from action MyController/Page/id I have hastily hashed up some html to show the image:

<img src="../image/@Model.Name" />

And then also with a link:

<a href="../image/@Model.Name">
  <img src="../image/@Model.Name" />
</a>

It works, but I am looking for a better way using @Html so resharper can help with navigation and validation, for the two above. I've tried this:

@Html.RenderAction("Image", "MyController", new { id = Model.Name })

But this doesn't compile, it says Expression must return a value to render.


回答1:


I think you're just looking for Url.Action(), which returns an URL to an Action:

<img src="@Url.Action("Image", "ImageController", new { id = Model.ImageID })" />



回答2:


You can use Url.Action() in the src attribute

 <img src='@Url.Action("Image", "ImageController", new { imageId = Model.Id })' alt='MyImage' />


来源:https://stackoverflow.com/questions/19728199/correct-way-to-show-an-image-that-comes-from-a-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!