Cannot find definitions of editor-label and editor-field in MVC 4, did MS remove it? Why?

后端 未结 1 1558
醉酒成梦
醉酒成梦 2021-01-22 00:18

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

相关标签:
1条回答
  • 2021-01-22 01:12

    Well there are a couple of options you can take:

    Wrap the elements in a class

    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 { /**/ }
    

    Add them back with JavaScript

    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');
    }
    

    Modify the editor templates

    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" />
    

    Pass in 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" })
    

    Further reading

    • My blog post - ASP.NET MVC display and editor templates
    0 讨论(0)
提交回复
热议问题