Reputation: 1081
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.
Upvotes: 5
Views: 15645
Reputation: 11203
You were very close. In order to confirm right syntax, always reference to 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" />
}
There is a simpler way if you don't want to worry about all the right html structure and css classes required by Bootstrap being applied: TwitterBootstrapMVC
With that you'd write something like this:
@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())
}
or something like this if you want it to render with prepends and appends:
@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()
}
using this library for Bootstrap 3 is not free, but you might find it cheaper than the time you spend figuring out syntax required by Bootstrap on your own. There is also a Trial version if you want to try it out first.
Disclaimer: I'm the author of TwitterBootstrapMVC
Upvotes: 17