Search code examples
asp.net-mvc-3razormvc-editor-templatesdisplay-templatescustom-data-type

How to create and implement a custom datatype in mvc3 razor


I googled the problem too many times. But I couldnt find any solution to do this.

I want to create a custom DataType with a default EditorTemplate and DisplayTemplate for use in mvc3 razor.

Model

[DataType("MyCustomDataType")]
public MyType Property { get; set; }
// I mean by MyType any type of data: string, int, datetime and so on

View - Razor

@Html.DisplayFor(m => m.Property)
//or
@Html.EditorFor(m => m.Property)

Actually I want to create a reuseable datatype with default editor-template and display-template.

Do you have any suggestion please? Can you give me a useful link or if you can, a simple example please? Thanks in advance.


Solution

  • this is an excellent tutorial for custom editor/display template. Although its not in razor syntax, its easily convertible.

    If you want to create editor template depending on Datatype attribute, you can get the attribute value using ViewData.ModelMetadata.AdditionalValues["DataTypeAttribute"]

    If the value is your custom datatype value, do what ever you want. Otherwise, do the default.

    Not sure if it is a good idea. But it should work.