1

The following code snippet effectively represents items in a large form. My objective is to refactor it down.

<div class="span3">
<ul style="list-style-type: none">
    <li><b>Description</b></li>
    <li>
        <textarea style="width: 100%;" rows="4">@Model.Item.Description</textarea>
    </li>
</ul>
</div>
<div class="span3">
<ul style="list-style-type: none">
    <li><b>Truck</b></li>
    <li>
        @Html.DropDownListFor(model => model.Item.ShippingTruckId, new SelectList(Model.ShippingTrucks, "Id", "Truck"))
    </li>
</ul>
</div>
<div class="span3">
<ul style="list-style-type: none">
    <li><b>Cost</b></li>
    <li>
        <input value="@Model.Item.Cost"/>
    </li>
</ul>
</div>

Two approaches I've considered is a partial view and an HTML helper. Ultimately though, how do a pair those down into a smaller easier to maange segment. I'm generally either going to have that same structure with either an input, a text area, a drop down, or in some cases a label. Is there another, superior, approach I haven't thought of, or any inherent disadvantages/advantages/challenges to one I've mentioned?

Seth
  • 954
  • 1
  • 15
  • 42

1 Answers1

2

With reflection you can read all the properties and EditorFor to create the elements:

Example for Reflection I
Example for reflection II

With first example:

@foreach (var property in Model.EnumerateProperties())
{
    <div class="span3">
    <ul style="list-style-type: none">
        <li><b>@Html.LabelForProperty(Model,property);</b></li>
        <li>
            @Html.EditorForProperty(Model,property);
        </li>
    </ul>
    </div>
}

And here or here you can see how to use editor template for diferent type of property or use UIHint.

Edit for this comment:: "How do you handle the dropdownlists this way?"

in this case I can think of a solution, but a bit complex. you can on the property put an attribute, something like:

[ItPropertyHaveAList("PropertyWithListList")]
public int PropertyWithListId { get; set; }

public IEnumerable<SelectListItem> PropertyWithListList { get; set; }

then the extension EditorForProperty you can detect if the property has this attribute like this example:

[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
public string FirstName {get;set;}

StringLengthAttribute strLenAttr = 
  typeof(Person).GetProperty("FirstName").GetCustomAttributes(
  typeof(StringLengthAttribute), false).Cast<StringLengthAttribute>().Single();


int maxLen = strLenAttr.MaximumLength;

In this attribute you put the method from list data to create a dropdownlists. See this response to see how create template for dropdownlists.

Community
  • 1
  • 1
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
  • This is a fantastic answer, and very helpful. Before I accept, I have one question - How do you handle the dropdownlists this way? – Seth Jul 18 '13 at 18:06