【问题标题】:How to concatenate two strings in a <img> src tag?如何在 <img> src 标签中连接两个字符串?
【发布时间】:2013-04-11 11:04:33
【问题描述】:

在这里,我想在 &lt;img&gt; 标记内连接两个字符串。这个怎么办??

<img src=" "/partners" + @item.AdPath" alt="" id="adimg" title="@item.AdName"  width:"50px" height="50px"/>

有什么建议吗?

【问题讨论】:

  • 我在您的&lt;img&gt; 标签中看到了许多字符串。您需要连接哪些?或者换句话说:你期望什么输出?
  • 我想将 /partners 与 @item.AdPath 连接起来
  • 输出应该像 /partners+adpathvalues
  • 您是否尝试过使用服务器标签&lt;%= item.AdPath %&gt;
  • @RJK:他用的是razor,不是asp,所以@是表示服务器端逻辑的标签。

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


【解决方案1】:

在 HTML5 中我做到了:

 <img src="{{basePath  + Data.id +'/' + Data.id + '_0.jpg'}}">

basePathData.id 是变量,'' 之间的任何内容,例如 '/''_0.jpg',正是我想要连接到这些变量的内容。

【讨论】:

    【解决方案2】:

    我有一个类似的子文件夹图像文件访问问题,但以下代码格式适用于我的应用程序。

    <img src='<%#: String.Format("~/partners/{0}", item.AdPath) %>'
     alt="" id="adimg" title="<%#:item.AdName%>"  width:"50px" height="50px"/>
    

    【讨论】:

      【解决方案3】:

      可以这样做:

      第一:

      <img src="@("/partners" + item.AdPath)" alt="" id="adimg" title="@item.AdName"  width:"50px" height="50px"/>
      

      第二:

      <img src="/partners@(item.AdPath)" alt="" id="adimg" title="@item.AdName"  width:"50px" height="50px"/>
      

      【讨论】:

        【解决方案4】:

        您应该能够做到这一点:

        <img src="/partners+@(item.AdPath)" alt="" id="adimg"
            title="@item.AdName"  width:"50px" height="50px"/>
        

        Razor 引擎会将@item.AdPath 替换为实际值,为您提供src="/partners+[value]"

        由于 Razor 表达式是唯一要解析的内容,因此您不必尝试将字符串连接逻辑处理到标记中 - 只需将 Razor 表达式放入您希望值出现的位置。

        编辑:或者,如果您不想要加号(从您的 cmets 中不清楚):

        <img src="/partners@(item.AdPath)" alt="" id="adimg"
            title="@item.AdName"  width:"50px" height="50px"/>
        

        或者,您可以尝试使用String.Format

        <img src="@String.Format("/partners{0}", item.AdPath)" alt="" id="adimg"
            title="@item.AdName"  width:"50px" height="50px"/>
        

        【讨论】:

        • 如果我给它这样的 /partners@item.AdPath.......我得到这样的 /partners@item.AdPath...而不是 @item.AdPath 值跨度>
        • 我需要带有 @item.AdPath 值的 /partners 字符串
        • 奇怪,应该可以。您的其他 Razor 表达式是否已解析?尝试使用 String.Format 或将 Razor 表达式括在括号中的最后一次更新。
        • /partners@item.AdPath 不起作用的原因是 razor 对电子邮件地址使用智能识别。它已经评估这是一个电子邮件地址,不应该被解释为一个剃刀表达,这就是为什么那个会出错。所以 int hat case 可以使用@(abc.xyz)syntax,让razor 明白它不是电子邮件地址。
        • 如果您使用的是String.Format - src="@String.Format("/partners{0}{1}", item.AdPath, item.Status)"
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-11
        • 1970-01-01
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        • 2021-09-20
        • 2020-07-13
        相关资源
        最近更新 更多