Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What about Lists or IEnumerables? #14

Open
oliverjanik opened this issue Apr 2, 2014 · 2 comments
Open

What about Lists or IEnumerables? #14

oliverjanik opened this issue Apr 2, 2014 · 2 comments

Comments

@oliverjanik
Copy link

How do I tell this formatter which view to use? Naming conventions don't work because it looks for "List`1.cshtml".

I can't really annotate IEnumerable with ViewAttribute.

And I can't use ViewResult since I rely on content negotiation to return proper media type.

I would suggest a per Action attribute. Or introduce smarter naming convention.

@oliverjanik
Copy link
Author

If anyone comes across this I've overridden the convention if the type is IEnumerable.

    public class WrappedViewLocator : IViewLocator
    {
        private readonly RazorViewLocator razor = new RazorViewLocator();

        public string GetView(string siteRootPath, IView view)
        {
            var itemType = GetEnumerableType(view.ModelType);
            if (itemType != null)
                view = new ReimplementedView(view.Model, view.ModelType, itemType.Name + "List");

            return razor.GetView(siteRootPath, view);
        }

        private static Type GetEnumerableType(Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                return type.GetGenericArguments()[0];


            return type
                .GetInterfaces()
                .Where(intType => intType.IsGenericType && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                .Select(intType => intType.GetGenericArguments()[0])
                .FirstOrDefault();
        }
    }

    public class ReimplementedView : IView
    {
        public ReimplementedView(object model, Type modelType, string viewName)
        {
            Model = model;
            ModelType = modelType;
            ViewName = viewName;
        }

        public object Model { get; private set; }
        public Type ModelType { get; private set; }
        public string ViewName { get; private set; }
    }

@panesofglass
Copy link
Member

Is this generally re-usable for all purposes? If so, would you mind adding this as a PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants