How to use partial view from another project in asp.net mvc

若如初见. 提交于 2019-12-01 15:13:45

问题


I have two MVC projects one as a parent project and the other as a child project. The child project adds reference to the parent project. I like to use partial views from the parent project from the child project something like -

@Html.Partial("_GenericGreeting") <-- in child project

_GenericGreeting.cshtml <-- is in parent project

The child project is the project that starts up. Parent project i mean is like a base/shared project. RazorGenerator has been installed on both projects and each projects can be compiled into single assembles.

When I ran the project, i'm only getting this following error.

The partial view '_GenericGreeting' was not found or no view engine supports the searched locations.

If i copy the partial view and paste it into the child project it's fine but i don't want to duplicate the files.

I have tried this post but no luck but maybe i'm not adding it right.


回答1:


Not really good, but simple solution that can solve your problem. One of overloads @Html.Partial() allows you to write full path to your View.

Something like this:

@Html.Partial("~/View/Shared/_GenericGreeting.cshtml")



回答2:


I accepted teo's answer. He helped me and gave me clue to the problem. But there are few important things to check.

One thing I wasn't aware is the generated cshtml files have properties called PageVirtualPathAttribute. One problem i couldn't get the right combination is because i was getting the path wrong.

Another thing to look is this class which is auto generated when you installed RazorGenerator and it is in your App_Start folder.

public static class RazorGeneratorMvcStart {
        public static void Start() {
            var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly) {
                UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages. 
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
        }
    }

However this line has an overload method to define path to your compiled view. My shared project was created by someone else and he put this path in it.

var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly, @"~/Areas/Cart/", null)

Once I have those bits checked, I just need to use like the following in my view as teo suggested.

@Html.Partial("~/Areas/Cart/Views/Home/_GenericGreeting.cshtml")


来源:https://stackoverflow.com/questions/31920735/how-to-use-partial-view-from-another-project-in-asp-net-mvc

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