【问题标题】:Razor Nest Elements TwitterBootstrapMVC5Razor 嵌套元素 Twitter Bootstrap MVC 5
【发布时间】:2015-10-28 21:32:11
【问题描述】:

如何使用 Razor 嵌套 HTML 元素?

以这个简单的 HTML 为例

<label class="input">
    <i class="icon-prepend fa fa-user"></i>
    <input type="text" name="fname" placeholder="First name">
</label>

在 Razor 中相当于什么?对于任何认为这太宽泛的人来说。我基本上想注册@Html.Label() 然后继续为它设置子属性,其中包括一个图标和文本框。

是否有可能用剃须刀实现我想要实现的目标?

它会创建这样的东西

我试图弄清楚但失败了。这是我得到的最好的。

<label class="input">
    @Html.Bootstrap().Icon("icon-prepend fa fa-user")
    @Html.Bootstrap().TextBoxFor("fname", htmlattributes: new { placeholder = "First name" })
</label>

我也希望在 razor 中创建标签。

【问题讨论】:

  • 唯一适用于此的“开箱即用助手”是@Html.TextBoxFor(),它将创建&lt;input type="text" ... /&gt; 元素。您可以创建一个自定义 html 辅助扩展方法(例如)@Html.TwitterTextBoxFor(m =&gt; m.fname),它会呈现该 html。

标签: html asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-5


【解决方案1】:

你可以这样做:

<label class="input">
    <i class="icon-prepend fa fa-user"></i>
    @Html.TextBoxFor("fname", htmlattributes: new { placeholder = "First name" })
</label>

【讨论】:

  • 那么这是最接近使用剃须刀的 id 吗?所以基本上只是将剃刀文本框功能包装在标签项中。
【解决方案2】:

创建一个custom HTML helper。 HTML 帮助程序的输出将是 @CarlosAraujo 建议的:

<label class="input">
    <i class="icon-prepend fa fa-user"></i>
    @Html.TextBoxFor("fname", htmlattributes: new { placeholder = "First name" })
</label>

你可以这样称呼它:

@Html.MyCustomAwesomeTextBoxFor(...)

通过这种方式,您可以在代码中的任何位置封装和重用该组件。

【讨论】:

  • 我喜欢这种方式,你明明也可以传入一堆参数对吧?或者可能是整个@Html.TextboxFor()
  • 您不需要传递整个 '@Html.TextboxFor()',您应该将该代码放入新的自定义 HTML 帮助程序中。是的,您可以传递您需要的参数(可能只是输入的名称)。
  • 酷,只是考虑其他组件的可重用性,例如下拉菜单等。感谢您的回答。
  • @ShaneVanWyk 很高兴为您提供帮助。如果他们对您有帮助,请选择此答案或任何其他答案作为已选答案。
猜你喜欢
  • 2018-04-09
  • 2012-09-24
  • 1970-01-01
  • 2014-10-05
  • 2014-03-30
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
相关资源
最近更新 更多