通过html帮助器中的ajax提供图像

时间:2013-07-07 16:06:46

标签: c# asp.net-mvc asp.net-mvc-4 html-helper

我对一件事感到好奇。假设我在SQL数据库中保存图像(我知道不建议使用;最好的方法是只保存对其他地方保存的图像的引用,但我想问你一些关于这个特定情况的内容)。

我正在提供这样的文件:

 public ActionResult Serve(int id)
    {
        ......
        return File(img.Content, img.ContentType);
    }

我还制作了Html helper

   public static HtmlString ServeImage(this HtmlHelper html, int id)
    {
        var urlHelper= new UrlHelper(html.ViewContext.RequestContext);

        var tag= "<img  src='{0}' width='200' height='200' />";

        return new HtmlString(string.Format(imageTag, urlHelper.Action("Serve", "Image", new { id = id })));
    }

所以,当我想要展示一张图片的时候我会在这样的视图中写道:@Html.ServeImage(imageId)

我的问题是:* 有没有办法通过ajax调用urlHelper.Action("Serve", "Image", new { id = id })))仍然使用我的助手? *

我已经阅读了有关Ajax Helpers的内容,但我认为这对我没有帮助,而且我只剩下一个选项了。我需要放弃我的助手并像往常一样用ajax调用我的动作。这是正确的吗?

我的意思是:

$.ajax(function() { ..... });

1 个答案:

答案 0 :(得分:0)

您可以使用普通的img标签并将src设置为@ urlHelper.Action(“Serve”,“Image”,new {id = id})))

示例:

<img src='@urlHelper.Action("Serve", "Image", new { id = id })' width='200' height='200' />