4

I'm creating an MVC 5 site using bootstrap 3.0.0. I'm having difficulty binding the model to an input field. I simply don't know the syntax for doing this.

The following code works functionally, but I lose bootstrap's styling.

<div class="control-group">
    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
    <div class="controls">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>

On the other hand, this block of code looks great, but I can't get the binding to work. @using (Html.BeginForm()) {

    <div class="input-group">
        <span class="input-group-addon">@Html.LabelFor(model => model.Name)</span>
        <input type="text" class="form-control" placeholder="Enter your name here..."/>
        <span class="input-group-addon">@Html.ValidationMessageFor(model => model.Name)</span>
    </div>

    <div class="form-actions no-color">
        <input type="submit" value="Create" class="btn btn-default" />
    </div>

    </fieldset>
}

So I need some assistance either getting the top block or bottom block to work. Either the right syntax to make it work functionally, or a slick method of attaching to the correct CSS in bootstrap to make it look attractive.

Any suggestions are welcome.

4

1 回答 1

16

你非常亲近。为了确认正确的语法,请始终参考Bootstrap Docs

@using (Html.BeginForm())
{
    <div class="form-group">
        <div class="input-group">
            <span class="input-group-addon">@Html.LabelFor(model => model.Name)</span>
            @Html.TextBoxFor(model => model.name, new { @class = "form-control", placeholder = "Enter your name here..." })
            <span class="input-group-addon">@Html.ValidationMessageFor(model => model.Name)</span>
        </div>
    </div>
    <input type="submit" value="Create" class="btn btn-default" />
}

如果您不想担心应用 Bootstrap 所需的所有正确的 html 结构和 css 类,有一种更简单的方法:TwitterBootstrapMVC

有了它,你会写这样的东西:

@using (var f = Html.Bootstrap().Begin(new Form().Type(FormType.Horizontal)))
{
    @f.FormGroup().TextBoxFor(m => m.Name).Placeholder("Enter your name here...")
    @f.FormGroup().CustomControls(Html.Bootstrap().SubmitButton())
}

或类似的东西,如果你希望它使用前置和附加来呈现:

@using (Html.Bootstrap().Begin(new Form()))
{
    @(Html.Bootstrap().TextBoxFor(m => m.Name)
        .Placeholder("Enter your name here...")
        .Prepend(Html.Bootstrap().LabelFor(m => m.Name))
        .Append(Html.ValidationMessageFor(m=> m.Name)))
    @Html.Bootstrap().SubmitButton()
}

为 Bootstrap 3 使用这个库不是免费的,但你可能会发现它比你自己花时间弄清楚 Bootstrap 所需的语法要便宜。如果您想先试用,还有一个试用版。


免责声明:我是 TwitterBootstrapMVC 的作者

于 2013-10-03T19:18:38.070 回答