IAmGroot
IAmGroot

Reputation: 13855

ASP.NET MVC 3: Editor templates for fields

<tr>
   <td>
        @Html.Label("Notes") </td><td> @Html.TextArea("Notes")
   </td></tr>
   <tr><td>
        @Html.Label("Action Date")</td><td> @Html.TextBoxFor(m => m.Due, new { @class = "dateTimePicker" })</td><td>
        @Html.ValidationMessageFor(m => m.Due)
   </td></tr>

Anyway I can create a template that will take any @HTML.Label, @Html.Textbox etc etc, and their for counterparts and place them into a table properly? without me having to polute all my views with table markups.

Upvotes: 2

Views: 4032

Answers (2)

Jesse
Jesse

Reputation: 8393

You most certainly can. I have pieced together a quick sample based upon your sample code:

Given a basic model:

public class Foo
{
    public string Notes { get; set; }

    [Required]
    [DisplayName("Action Date")]
    public DateTime Due { get; set; }
}

And this simple controller:

var model = new Foo { Notes = "Some Note String", Due = System.DateTime.Now };
return View(model);

You could call an editor template from your view:

 @Html.Editor("Editor", "Foo", Model)

Given this template:

@model StackExamples.Models.Foo

<table>
    <tr>
        <td>
            @Html.LabelFor(x => x.Notes)
        </td>
        <td>
            @Html.TextAreaFor(x=>x.Notes)
        </td>
    </tr>
    <tr>
        <td>
            @Html.LabelFor(x=>x.Due)
        </td>
        <td>
            @Html.TextBoxFor(m => m.Due, new { @class = "dateTimePicker" })
        </td>
        <td>
            @Html.ValidationMessageFor(m => m.Due)
        </td>
    </tr>
</table>

And have your output rendered as desired without the additional table markup in your views.

Upvotes: 2

Related Questions