【问题标题】:Umbraco - How to display an image from a media picker in the src of an IMG tag?Umbraco - 如何在 IMG 标签的 src 中显示来自媒体选择器的图像?
【发布时间】:2016-10-22 19:52:15
【问题描述】:

如何获取在 umbraco 中使用媒体选择器选择的图像的 url - 我找到了 umbraco 文档,其中强调媒体选择器的返回值是所选择项目的 ID。但这肯定是您用来向模板添加图像的方法吗?

我想做...

<div class="title" style="background-image:url(@Umbraco.Field("mediaPicker"))">
   <h1>...@Umbraco.Field("pageTitle")</p>
</div>

谢谢

【问题讨论】:

    标签: razor model-view-controller umbraco


    【解决方案1】:

    根据Umbraco Documentation,您有两个选择,我的建议是选择第一个,因为我相信在未来的版本中将不再支持动态。

    1。打字

    @if (Model.Content.HasValue("caseStudyImages"))
    {
        var caseStudyImagesList = Model.Content.GetPropertyValue<string>("caseStudyImages").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
        var caseStudyImagesCollection = Umbraco.TypedMedia(caseStudyImagesList).Where(x => x != null);
    
        foreach (var caseStudyImage in caseStudyImagesCollection)
        {      
            <img src="@caseStudyImage.Url" style="width:300px;height:300px" />      
        }                                                               
    }
    

    2。动态

    @if (CurrentPage.HasValue("caseStudyImages"))
    {
        var caseStudyImagesList = CurrentPage.CaseStudyImages.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        var caseStudyImagesCollection = Umbraco.Media(caseStudyImagesList);
    
        foreach (var caseStudyImage in caseStudyImagesCollection)
        {
            <img src="@caseStudyImage.Url" style="width:300px;height:300px" />
        }
    }
    

    id 用于将媒体对象作为TypedMedia 对象取回,从那里您可以访问图像网址。

    【讨论】:

    • 谢谢你 - 我会看看我是否可以让它工作 - 你是否可以使用 @Umbraco.NiceUrl 获取图像的 url,就像你能够获得通过媒体选择器选择的节点的 url? - @Umbraco.NiceUrl(Model.Content.GetPropertyValue("contentPicker"))
    • 我从来没有这样尝试过,但NiceUrl 只需要一个 NodeId,如果您将媒体选择器设置为单个项目,您将传递它,这样您就可以做到。
    • 请务必在使用前检查您是否获得了有效的输入图像,以防在您尝试使用其任何值之前未设置或选择它,只是提示
    【解决方案2】:

    你可以使用Umbraco.Media(),它是动态的,就像Umbraco.Content()一样

    <div class="title" style="background-image:url(@Umbraco.Media(CurrentPage.MediaPicker).Url)">
       <h1>...@CurrentPage.PageTitle</p>
    </div>
    

    【讨论】:

      【解决方案3】:

      显示图像的简单方法:

      //Get the ID of the Field
      var mediaId = Umbraco.Field("NameOfYourField");
      //Get the MediaType to Write the URL
      var media   = Umbraco.Media(mediaId.ToString());
      //Salve the Path into the Image
      var image   = media.Url;
      
      <img src="@image">
      

      简单易行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 2014-03-11
        • 2013-12-29
        • 2021-10-02
        • 1970-01-01
        相关资源
        最近更新 更多