Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 719
Laurence Avatar asked Aug 10 '15 13:08

Laurence


2 Answers

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")
like image 150
Laurence Avatar answered Oct 13 '22 03:10

Laurence


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")
like image 29
teo van kot Avatar answered Oct 13 '22 02:10

teo van kot