如何仅指定名称来设置 Razor 布局文件? [英] How to set Razor Layout file just specifying the name?

查看:67
本文介绍了如何仅指定名称来设置 Razor 布局文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先介绍一下上下文.当您调用 Html.RenderPartial 时,您发送视图名称,该视图将在 RazorViewEngine.PartialViewLocationFormats 指定的位置搜索:

First a little context. When you call Html.RenderPartial you send the View name, that view will be searched at locations specified by RazorViewEngine.PartialViewLocationFormats:

Html.RenderPartial("Post", item);

在 Razor 页面设置 Layout 属性时,不能只说名字,需要指定路径.如何只指定名称?

When you set the Layout property at Razor page, you can´t just say the name, you need to specify the path. How can I just specify the name?

//Layout = "_Layout.cshtml";
Layout = "_Layout"; //Dont work

我需要这个,因为我覆盖了 RazorViewEngine.MasterLocationFormats.

I need this because I overrided the RazorViewEngine.MasterLocationFormats.

目前我在控制器上指定主站:

Currently I am specifying the Master at controller:

return View("Index", "_Layout", model);

这可行,但我更喜欢在 View 中执行此操作.

This works, but I prefer to do this at View.

推荐答案

没有直接的办法,但是我们可以写一个像RenderPartial()"这样的HtmlExtension,它会在运行时给出完整的布局路径.

There is no direct way to do it, But we can write an HtmlExtension like "RenderPartial()" which will give complete layout path at runtime.

public static class HtmlExtensions
{
    public static string ReadLayoutPath<T>(this HtmlHelper<T> html,string layoutName)
    {
        string[] layoutLocationFormats = new string[] {
        "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.cshtml"
        };

        foreach (var item in layoutLocationFormats)
        {                
            var controllerName= html.ViewContext.RouteData.Values["Controller"].ToString();
            var resolveLayoutUrl = string.Format(item, layoutName, controllerName);
        string fullLayoutPath = HostingEnvironment.IsHosted ? HostingEnvironment.MapPath(resolveLayoutUrl) : System.IO.Path.GetFullPath(resolveLayoutUrl);
        if (File.Exists(fullLayoutPath))
            return resolveLayoutUrl;
        }
        throw new Exception("Page not found.");
    }
}

在视图中我们可以将其用作,

In the view we can use it as,

@{
Layout = Html.ReadLayoutPath("_Layout");   
}

这篇关于如何仅指定名称来设置 Razor 布局文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆