ASP.NET MVC 4 Editor Template for basic types

房东的猫 提交于 2019-12-17 10:23:19

问题


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 ?


回答1:


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.




回答2:


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 ?



来源:https://stackoverflow.com/questions/14655930/asp-net-mvc-4-editor-template-for-basic-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!