سؤال

I am writing an Html extension to render partial views dynamically (view name/path is provided by CMS at runtime).

Within my extension I need to determine the name or path to the outermost view containing the partial in the case where a view contains a partial contains another partial contains yet another partial- I need to learn the identity of the parent view.

Within the extension method I know I can get the immediate parent through the HtmlHelper.ViewDataContainer property. That tells me the context of the the currently executing extension. What I need to be able to do is iterate up to its parent view if there is one.

هل كانت مفيدة؟

المحلول

If you search for controller and action, you can get it like so:

string action = html.ViewContext.RouteData.Values["action"].ToString();
string controller = html.ViewContext.RouteData.Values["controller"].ToString();
string url = "~/" + controller + "/" + action;

To get the immediate view (including partial), it is like so:

var webPage = HtmlHelper.ViewDataContainer as WebPageBase;
var virtualPath = webPage.VirtualPath;

To get the first view path (the master view containing all partial views):

var viewPath = ((System.Web.Mvc.BuildManagerCompiledView)(htmlHelper.ViewContext.View)).ViewPath;

نصائح أخرى

I know this has been answered and it's over a year old, but would using ViewData to pass the view names down from the top to the furthest nested partial view work? So in the ParentView you'd do something like:

@{
    ViewData["ResourcePath"] = "ParentView";
    Html.RenderPartial("Partial1", Model, ViewData);
}

And then in your Partial1 view:

@{
    ViewData["ResourcePath"] = ViewData["ResourcePath"] + "_Partial1";
    Html.RenderPartial("Partial2", Model, ViewData);
}

And so on until you reach the level where you need to get the string resource.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top