Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 Editor Template for basic types

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 ?

like image 986
Sam Avatar asked Feb 01 '13 22:02

Sam


2 Answers

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.

like image 83
Darin Dimitrov Avatar answered Nov 10 '22 11:11

Darin Dimitrov


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 ?

like image 1
Olivier Albertini Avatar answered Nov 10 '22 11:11

Olivier Albertini