ASP.NET MVC 4 Editor Template for basic types
Asked Answered
S

2

45

I've created a template for Number input and if I do

@Html.EditorFor(model => model.SomeValue, "Number")

it works fine and the template is used.

However that doesn't work:

@Html.EditorFor(model => model.SomeValue)

Why do I need to specify the name of the Editor Template for basic types ?

Skyrocket answered 1/2, 2013 at 22:14 Comment(0)
P
93

Editor templates work by convention. The name of the template must match the name of the type. So for example if SomeValue is an int type you could write a custom editor template at ~/Views/Shared/EditorTemplates/Int32.cshtml which will be used. In this case all integer types will use this custom template when you write @Html.EditorFor(model => model.SomeValue).

If you don't want to override all templates for integer types you could write a specific named template ~/Views/Shared/EditorTemplates/Number.cshtml that you could use only for some properties by specifying this template name as second argument to the EditorFor helper: @Html.EditorFor(model => model.SomeValue, "Number") or by decorating your view model property with the [UIHint] attribute:

[UIHint("Number")]
public int SomeValue { get; set; }

and then simply using @Html.EditorFor(model => model.SomeValue) will render the Number.cshtml custom template.

I would also recommend you reading Brad Wilson's blog post about the default templates in ASP.NET MVC.

Perak answered 2/2, 2013 at 22:49 Comment(4)
that's great, I'm going to use the UIHint attribute. Thanks a lot !Skyrocket
The second file name should be ~/Views/Shared/EditorTemplates/Number.cshtml. The dot before Number.cshtml must be replaced with a slash.Lenni
Can you get the default .cshtml files for the built in editors if you want to make a small change and use those with the sight modifications? The link provided the .ascx option.Gladsome
@Xaxum, yes you can do that with Razor templates as well. All you have to do is translate the code shown in the linked article to Razor which is a trivial task.Perak
Y
1

In your Editor Template, you must have the same type Example :

model.SomeValue is type of loremIpsumObject

In your EditorTemplate you are :

  @model YourNamespaceWhereIsYourClass.loremIpsumObject
  ...And your code in your editorTemplate....

you can find an example here for datetime

It helps you ?

Yamashita answered 2/2, 2013 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.