Usually I render my forms by @Html.RenderModel, but this time I have a complex rendering logic and I render it manually. I decided to create a editor template for one property.
What type is the "x.SomeProperty"? I'm gonna assume for now it's type is called Property.
MyModel.cs
public class MyModel
{
public Property SomeProperty { get; set; }
}
Property.cs
public class Property
{
[Display(Name="Foo")]
public int Value { get; set; }
}
Views/Shared/EditorTemplates/Property.cshtml
@model MvcApplication1.Models.Property
@Html.LabelFor(model => model.Value)
@Html.EditorFor(model => model.Value)
@Html.ValidationMessageFor(model => model.Value)
MyView.cshtml
@Html.EditorFor(model=>model.SomeProperty)
If you don't provide templatename for EditorFor helper it finds editortemplate which name matches SomeProperty's type.
Update:
To make a custom editortemplate for string you do:
Model
public class MyModel
{
public string SomeProperty { get; set; }
}
View:
@Html.EditorFor(model => model.SomeProperty,"Property")
Or alternatively:
Model:
public class MyModel
{
[DataType("Property")]
public string SomeProperty { get; set; }
}
View:
@Html.EditorFor(model => model.SomeProperty)
Views/Shared/EditorTemplates/Property.cshtml:
@model string
@Html.Raw("I'm using property editortemplate:")
@Html.Label(ViewData.ModelMetadata.PropertyName)
@Html.Editor(ViewData.ModelMetadata.PropertyName)
@Html.ValidationMessage(ViewData.ModelMetadata.PropertyName)