The code I am looking to produce is similar to:
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
Using something like this:
@Html.LabelledTextBoxFor(model => model.EmailAddress)
Where the label text get derived from model.EmailAddress
This would be done using Data Annotation e.g.
[Displayname("Email Address]
What is the best way to accomplish this?
Will this affect the auto generated client side JS validation using jquery val?
I would use
@Html.EditorFor
template. So create EditorTemplates folder in Views/Shared in your MVC project with a name EmailAddress.cshtml - it will display this template for every[DataType(DataType.EmailAddress)]
defined in your model.So: EmailAddress.cshtml should look sth like this:
Model should look like this:
Note here, that I've used Prompt property of Display metadata, which I linked to placeholder via
ViewData.ModelMetadata.Watermark
inEmailAddress.cshtml
.Html.LabelFor
will always take property Name from Display and DataType is needed for linking between EditorTemplates and model property.And invoke all this "magic" by using
on a page, where you use
SomeMode
model.I hope this does make sense.
No need to reinvent the wheel. Check out TwitterBootstrapMVC.
The code you'd be writing would look similar to the below:
Disclaimer: I'm the authot of TwitterBootstrapMVC.
TwitterBootstrapMVC for use on Bootstrap 3 is not free. See details on the website.
The Data Annotations go in the viewmodel above the property:
Then, in your view, you'd have something like this:
I wrote an extension method, maybe this might help:
You can use default display attribute to specify display name.There is no need for custom attributes.And you can use this extension like this:
Note: I have tried myself and it is working correctly.
Update: More simple version