ASP.NET MVC editor template for property

后端 未结 2 1527
余生分开走
余生分开走 2021-02-19 22:51

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.

2条回答
  •  孤街浪徒
    2021-02-19 22:56

    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)
    

提交回复
热议问题