When faced with the same problem in the past, I created the following solution:
First, decorate your (specific) view model with the ExportMetadata attribute, which indicates the name of the view to be used. For instance:
[ExportMetadata("View", "Ontario")] public sealed class OntarioViewModel : ProvinceViewModel { } [ExportMetadata("View", "Quebec")] public sealed class QuebecViewModel : ProvinceViewModel {}
Then add the HtmlHelper to the following Partial method:
public static MvcHtmlString Partial<T>(this HtmlHelper htmlHelper, T model, string prefix = null) { var modelType = typeof (T); var partialAttr = modelType.GetCustomAttributes<ExportMetadataAttribute>().SingleOrDefault(x => x.Name == "View"); if (partialAttr == null) throw new Exception(modelType.Name + " doesn't define any view to be used"); var partialName = (prefix ?? String.Empty) + partialAttr.Value; return htmlHelper.Partial(partialName, model, htmlHelper.ViewData); }
Then use it:
@Html.Partial(currentProvince);
And in case your partial files are in some subdirectory:
@Html.Partial(currentProvince, "Partials/")
(If you need help registering a custom HTML helper, see fooobar.com/questions/118700 / ... )
source share