Search code examples
asp.net-mvchtmlscaffoldingasp.net-mvc-scaffolding

MVC4 - How to rearrange generated fields created by Scaffolding


I have a .cshtml file created by MVC4 scaffolding that looks something like this:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>BicycleSellerListing</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.BicycleManfacturer)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ManufacturerList")
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.BicycleType)
        </div>
        <div class="editor-field">
            @Html.DropDownList("TypeList")
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ListingPrice)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ListingPrice)
            @Html.ValidationMessageFor(model => model.ListingPrice)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Comments)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Comments)
            @Html.ValidationMessageFor(model => model.Comments)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

Instead of the labels and columns being generated in a single vertical column, I would like to rearrange this so that I have labels in one column and editor fields in a second column (more of a traditional data entry form). I am very new to MVC 4 and HTML5 and don't really know how to go about doing this. If someone could help me rearrange this .cshtml code to accomplish this, I would be very thankful.


Solution

  • Here is one way using float:left and :before

    http://jsfiddle.net/fdLca/

    .editor-label {
        float:left;
        width:20%;
    }
    
    .editor-label:before {
        clear:left;
    }
    
    .editor-field {
        float:left;
        width:80%;
    }
    

    To get around using :before if you needed to support older IE (< 9) then you can add an element purely being used to clear in between each field and label.

    http://jsfiddle.net/fdLca/1/

    HTML

    <div class="editor-label">
        label1
    </div>
    <div class="editor-field">
        @Html.DropDownList("ManufacturerList")
    </div>
    
    <div class="clear"></div>
    

    CSS

    .clear {
        clear:left;
    }