将引导程序样式放入MVC中的文本框以用于搜索框

Lev*_*att 0 asp.net-mvc-4 twitter-bootstrap

我有一个搜索框,我想用Bootstrap样式自定义.textboxaspx中的代码是:

@Html.TextBox("SearchString")
Run Code Online (Sandbox Code Playgroud)

但我得到textbox一个标准风格.否则,搜索器的按钮显示为带有以下代码的引导样式:

<button class="btn" type="submit">Buscar</button>
Run Code Online (Sandbox Code Playgroud)

所以我bootstrap library在我的项目中有参考.获得textbox正确风格的最佳方法是什么?

先谢谢你.

Tru*_*ech 6

您可以通过将匿名对象传递给助手构造函数中的htmlAttributes属性来向Html助手添加类或ID.

@Html.TextBox("txtBox", null, new { @class = "your class name here", id = "your id name here" })
Run Code Online (Sandbox Code Playgroud)

在Bootstrap中,您可能希望使用类form-group和form-control.文档中的更多信息http://getbootstrap.com/css/


Daw*_*wan 6

你可以这样做:

@Html.TextBox("SearchString", null, new {@class="form-control"})
Run Code Online (Sandbox Code Playgroud)

如果要将按钮附加到文本框?

 <div class="input-group">
      <span class="input-group-btn">
        <button class="btn btn-default" type="button">Go!</button>
      </span>
      <input type="text" class="form-control" placeholder="Search for...">
</div>
Run Code Online (Sandbox Code Playgroud)

http://getbootstrap.com/components/#input-groups-buttons

你替换你<input>@Html.TextBox("SearchString", null, new {@class="form-control"})

 <div class="input-group">
      <span class="input-group-btn">
        <button class="btn btn-default" type="button">Go!</button>
      </span>
      @Html.TextBox("SearchString", null, new {@class="form-control"})
</div>
Run Code Online (Sandbox Code Playgroud)

使用 HTML 助手:

如果你想要一个用于 Bootstrap TextBox 的 HTML Helper,你可以这样做:

public static class MyHtmlHelpers
{
    public static MvcHtmlString BootStrapTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, 
         Expression<Func<TModel, TProperty>> expression)
    {
        return helper.TextBoxFor(expression, new { @class = "form-control" });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用:

@Html.BootStrapTextBoxFor(model => model.FirstName)
Run Code Online (Sandbox Code Playgroud)