问题
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