How can I use Bootstrap button addons in my MVC vi

2019-04-07 10:04发布

问题:

I'm having difficulty getting Bootstrap's button addons to work in my MVC view. I'm using the latest NuGet version of ASP.NET MVC (5.1 rc1) and Bootstrap (3.03).

I have the following in my view (now that I've pared it back to just hand-coded HTML rather than using Html.EditorFor(), in an attempt to getting it to work):

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true)

        <div class="row">
            <div class="col-lg-6">
                <div class="input-group">
                    <input type="text" class="form-control" />
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button">Go!</button>
                    </span>
                </div>
            </div>
            <div class="col-lg-6">
                &nbsp;
            </div>
        </div>

This generates the following HTML:

<form action="xxx" method="post">
<input name="__RequestVerificationToken" type="hidden" value="T3k..." />
<div class="form-horizontal">
    <div class="row">
        <div class="col-lg-6">
            <div class="input-group">
                <input type="text" class="form-control" />
                <span class="input-group-btn">
                    <button class="btn btn-default" type="button">Go!</button>
                </span>
            </div>
        </div>
        <div class="col-lg-6">
            &nbsp;
        </div>
    </div>
</div>
</form>

The problem is that, when this is displayed in the browser (Chrome 32 / IE 11), there's a big gap between the input box and the button. Like this:

If I reduce the size of the div surrounding the input-group div to col-lg-3 or smaller, it's fine. But anything larger than that leaves a gap.

It's as though there's a maximum size on the input - and indeed, all my inputs do seem to be smaller their container div...

What could be causing this?

回答1:

The default Site.css stylesheet that comes with a new MVC 5 project has a rule that limits the max-width of inputs. What you're getting is the result of the control spanning the full available width like it's supposed to, but then the input, itself, is being constrained to a defined width. Just comment out that piece of the stylesheet and everything will work as it should.

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

It's a pretty egregious shortcut the team seems to have taken in order to quickly build the sample site.