While I used to work with MVC 3, I took some portions of my previous project and embedding them into new MVC 4 template. Apparently the two most used CSS class definitions
Well there are a couple of options you can take:
Wrap all your inputs in a div
and change your styles to target that div
instead of .editor-label
and .editor-field
.
So HTML
<label class="editor-label">blah</label>
<input class="editor-field" />
Becomes
<div class="editor">
<label class="editor-label">blah</label>
<input class="editor-field" />
</div>
And your CSS
.editor-label { /**/ }
.editor-field { /**/ }
Becomes
.editor label { /**/ }
.editor input,
.editor select { /**/ }
You may be able to get away with using some JavaScript to add the classes back in.
Demo on jsFiddle
var content = document.getElementById('content');
var labels = content.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
labels[i].classList.add('editor-label');
var id = labels[i].getAttribute('for');
var input = document.getElementById(id);
input.classList.add('editor-field');
}
I wrote a blog post on how to modify display and editor templates a few months ago allowing custom HTML to be output from HtmlHelper.EditorFor()
and HtmlHelper.DisplayFor()
. This would allow you to put the classes back in where they were. This method may be more trouble than it's worth for your situation though.
Basically you can place a custom view in at the location Views/Shared/EditorTemplates/
named based on the type you want to override, for example string.cshtml
for string
. An example view for string
could be:
string.cshtml
@model string
@{
var id = ViewData.TemplateInfo.GetFullHtmlFieldId(Model);
}
<label class="editor-label" for="@id"></label>
<input type="text" class="editor-field" id="@id" />
htmlAttributes
You can't pass in a class to the htmlAttributes argument on EditorFor()
, but you can for LabelFor()
and TextBoxFor()
, etc. You could change all instances of EditorFor()
to their respective types and provide the classes in the call.
@Html.LabelFor(e => e.UserName, new { @class="editor-field" })
@Html.TextBoxFor(m => m.UserName, new { @class="editor-field" })