Common MVC4 patterns

I have several MVC4 projects and I would like to create a set of display / editor templates that are reused in those projects. I would like to create a generic project containing these templates and reference it in other projects.

So, I have views defined in my shared project as well as some other utilities:

Common
- Models
  - CommonMetadataAttribute.cs
- Views
  - Shared
    - EditorTemplates
      - Decimal.cshtml
      - Object.cshtml
      - Password.cshtml
      - String.cshtml
      - Switch.cshtml
    - ViewTemplates
      - Object.cshtml
      - Switch.cshtml
    - Error.cstml

      

And in my client project models I will have

using MobileWeb.Common

public class MyViewModel
{
    [UIHint("Switch")]
    [CommonMetadata(Theme = "foo")]
    public bool Enable { get; set; }
}

      

And in client project views, I could create custom editors by simply calling:

@model MyViewModel
...
@Html.EditorFor(model => model.Enable)

      

Ideally client projects can be overridden with their own templates and it will just fall back to generic templates if no specific project is defined.

I've looked into the portable scopes of MvcContrib, but I'm not sure if this will work as this is not the place and I really don't know how to do it. Before I go down this road, I would like to know what is the preferred way to do this?

+3


source to share


1 answer


Personally, I've always packaged templates as custom NuGets

. You put your own templates into NuGet, and when a user installs this NuGet in their project, they are automatically added to the correct folders in their application. And automatically, all EditorFor / DisplayFor calls throughout the application start using your own templates instead of the default ones.



This way you don't need to write some custom VirtualPathProviders (which break as soon as you precompile your application) to get Razor views embedded in 3rd party assemblies, etc. Another advantage of using NuGets is that the user has their own templates in their application and can easily change them if they are not satisfied with your work. And if he's really mad at you, all he needs to do is delete his NuGet to reset his app to its default state.

+3


source







All Articles