簡體   English   中英

從 _layout 發布的 Asp.net Core Razor 頁面

[英]Asp.net Core Razor Pages Post From _layout

我想要做的是使用從服務器會話填充為深色或淺色的復選框來更改應用程序的主題。

我知道可以使用 JavaScript 更改主題(樣式表),但這會導致加載默認的 Bootstrap 樣式表,然后是導致屏幕閃爍的深色樣式表。

我需要做的是從服務器返回 css 認為像下面這樣的 post 方法。

<div>
    <form id="theme-switcher" method="post">
        <div class="custom-control custom-switch">
            <input type="checkbox" class="custom-control-input" asp-for="IsDark" id="theme" />
            <label class="custom-control-label" for="theme">Theme</label>
        </div>
        <button id="change" type="submit" class="btn btn-primary">Change</button>
    </form>
</div>

上面的代碼可以在視圖組件或部分視圖中,但我似乎找不到發布自的方法。

_Layout.cshtml

@{
    bool isDark = HttpContext.HttpContext.Session.GetBoolean("IsDark");
}

<!-- Custom styles -->
@if (CultureInfo.CurrentUICulture.Name == "ar-LB")
{
    if (isDark)
    {
        <link rel="stylesheet" type="text/css" href="~/css/site-dark-rtl.css">
    }
    else
    {
        <link rel="stylesheet" type="text/css" href="~/css/site-rtl.css">
    }
}
else
{
    if (isDark)
    {
        <link rel="stylesheet" type="text/css" href="~/css/site-dark.css">
    }
    else
    {
        <link rel="stylesheet" type="text/css" href="~/css/site.css">
    }
}

到目前為止,我綁定的是部分視圖和視圖組件,但據我所知,部分視圖不能在OnPost后面添加代碼(將@page添加到部分視圖時,我得到的視圖數據不能為空,盡管模型和視圖數據設置)和視圖組件不能調用方法。

我應該使用什么方法?

無論您當前身在何處,您都可以發布到不同的路線。 因此,假設您有一個帶有代碼隱藏的 Razor 頁面SwitchTheme.cshtml ,可以在 POST 時切換主題,那么您可以調整<form>標簽以發布到該頁面:

<form asp-page="/SwitchTheme" method="post">
    <!-- … -->
</form>

請注意使用asp-page標簽助手生成帶有頁面鏈接的action屬性。

對於設計之類的更改,它不直接包含您想要顯示的某些頁面內容,您還可以使用一個簡單的控制器進行更改,然后重定向回來。 然后,您將改用asp-actionasp-controller標簽助手:

<form asp-controller="Utility" asp-action="SwitchTheme" asp-route-returnUrl="@Context.Request.Path" method="post">
    <!-- … -->
</form>
public class UtilityController : ControllerBase
{
    [HttpPost]
    public IActionResult SwitchTheme([FromForm] bool isDark, string returnUrl)
    {
        // switch the theme

        // redirect back to where it came from
        return LocalRedirect(returnUrl);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM