How to create a View template for MVC?

2.7k views Asked by At

I have been given the task of creating a template for Views in MVC. Basically, instead of many Views (CRUD) for each entity, we would only have one that accepts generic model and displays it in Edit/Display mode.

I have so far played around with IView, WebViewPage and ViewPage, but I can't seem to get anything to work. I also searched for something like this, but can't find anything useful really.

Specifically, I don't know which C# class I could overwrite/implement to get my desired effect. Can anybody help me out here?

1

There are 1 answers

3
wertzui On

When using MVC you normally have Razor Views (.cshtml). These come in 4 flavours:

  • Full Views
  • Partial Views
  • EditorTemplates
  • DisplayTemplates

From your question, I think, you want EditorTemplates.

Create a new View in Views/Shared/EditorTemplates and name it YourGenericModel.cshtml Inside this file write the first line:

@model YourGenericModel

You can now specify what should be rendered using the normal Razor syntax.

To Have your model displayed using your new View simply call

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