In asp.net-mvc what is the faster way to check if a partial view exists from Site.Master file?

leo*_*ora 0 c# asp.net-mvc asp.net-mvc-partialview

I have code in my Site.Master file that looks like this:

<% var menuName = StaticHelper.GetSiteMenuName(); %>
<%Html.RenderPartial("Menu" + menuName .ToUpper()); %>
Run Code Online (Sandbox Code Playgroud)

So if your menu name is "NewYork", it will look for a partial view called "MenuNewYork".

This works fine but in some cases now I don't have menu setup so i wanted to have it default to a default menu. I want something like this:

<% var menuName = StaticHelper.GetSiteMenuName(); %>
<% if (PartialViewExists("Menu" + menuName) { %>
      <%Html.RenderPartial("Menu" + menuName .ToUpper()); %>
<% }else { %>
      <%Html.RenderPartial("MenuDEFAULT"); %>
<% } %>
Run Code Online (Sandbox Code Playgroud)

Update

I found a solution here

public static bool DoesPartialViewExist(this HtmlHelper html, string partialViewName)
{
    var controllerContext = html.ViewContext.Controller.ControllerContext;
    ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName);
    return (result.View != null);
}
Run Code Online (Sandbox Code Playgroud)

I am just trying to see if there is a faster solution as I very conscious of any performance hit that this would take given this code would run on every single page load given its inside the site.master file.

Nko*_*osi 7

更新

在 Githup 上查看 MVC 的源代码后,内部已经缓存了获取视图和部分视图时找到的路径,这会使我最初的建议过早优化。

这意味着您找到并引用的答案...

public static bool DoesPartialViewExist(this HtmlHelper html, string partialViewName) {
    var controllerContext = html.ViewContext.Controller.ControllerContext;
    var viewEngineResult = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName);
    return (viewEngineResult.View != null);
}
Run Code Online (Sandbox Code Playgroud)

已经优化了。


原来的

您可以缓存该值以供将来查找以尝试提高多个请求的性能。

static IDictionary<string, bool> partialViewCache = new Dictionary<string, bool>();
public static bool DoesPartialViewExist(this HtmlHelper html, string partialViewName) {
    bool value = false;
    if (partialViewCache.TryGetValue(partialViewName, out value)) {
        var controllerContext = html.ViewContext.Controller.ControllerContext;
        ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, partialViewName);
        value = result.View != null;
        partialViewCache[partialViewName] = value;
    }
    return value;
}
Run Code Online (Sandbox Code Playgroud)

在上面一个静态字段用于保存值,但该方法可以很容易地使用另一种缓存机制。即 MemeoryCache、IMemoryCache 等,具体取决于平台。