1

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.

amiry jd
  • 27,021
  • 30
  • 116
  • 215
  • `Type` is a class in `C#`. I don't think you mean that one here, right? – Mohayemin Jul 28 '12 at 16:51
  • @Mohayemin you are right. I mean any type by `Type`. I update the question. – amiry jd Jul 28 '12 at 16:53
  • Well, your question suggests me you are looking for [this](http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html). Or I am missing something? – Mohayemin Jul 28 '12 at 17:02
  • @Mohayemin actually yep. I saw that link before and it was very very very useful. But I want to do something like that for a custom datatype. Have you any suggestion please? – amiry jd Jul 28 '12 at 17:23
  • Well, I do not clearly get the point of Custom Datatype. That link is valid for any datatype. Do you mean like the one that work for `[Datatype.Password]` where the text field become password field? – Mohayemin Jul 28 '12 at 17:26
  • ok ok ok ok I got it :D i have any idea and I'm going to implement it. Thanks to your suggestions. You can Post your suggestions all in one Answer, so I'll accept it as Answer. Thanks in advance – amiry jd Jul 28 '12 at 17:30

2 Answers2

2

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.

Mohayemin
  • 3,841
  • 4
  • 25
  • 54
  • 1
    +1 and accept. It is a good idea. I told you I have an idea, that is same as yours. I implement and run it, it works. So thanks to conversations, your guidance give me the idea. – amiry jd Jul 28 '12 at 22:06
0

You can create a new type, i.e. a Person class that you can include in the model that you send to the view. i.e. Model.Person.

By defining a new EditorTemplate and DisplayTemplate with the name Person. By default, calling @Html.EditorTemplateFor(x=>x.Person); will look for a EditorTemplate for the type.

Have a look at the following stackoverflow post on "How to use asp.net mvc Editor Templates"

Community
  • 1
  • 1
Pieter Germishuys
  • 4,828
  • 1
  • 26
  • 34