How to display Images using HtmlHelper Class- ASP.NET MVC

后端 未结 2 409
梦如初夏
梦如初夏 2021-01-15 05:51

I am currently stuck with this problem of displaying an image using HtmlHelper class.

Here is what i have.

I have a custom HtmlHelper class which supposed to

2条回答
  •  囚心锁ツ
    2021-01-15 06:07

    There are some problems with your controller action. It expects to pass the image as a byte array. In your helper class you are trying to generate an img tag pointing to this controller action and passing a byte array but this won't work because you cannot pass byte arrays using GET requests. You need to change this controller action so that instead of accepting a byte array it takes for example some identifier that allows you to fetch the image and write it to the output stream. Then your html helper will pass this identifier when generating the img tag.

    public FileContentResult GetPhoto(string imageId)
    {
        byte[] image = _repository.GetPhoto(imageId);
        return File(image, "image/jpeg");
    }
    

    And your helper:

    public static string Images(this HtmlHelper htmlHelper, string id,string alt)
    {
        var urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url; 
        var photoUrl = urlHelper.Action("GetPhoto", "Clinical", new { imageId = id });
        var img = new TagBuilder("img");
        img.MergeAttribute("src", photoUrl);
        img.MergeAttribute("alt", alt);
        return img.ToString(TagRenderMode.SelfClosing);
    }
    

    Which could be used in your view:

    <%= Html.Images("123") %>
    

提交回复
热议问题