简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM