【问题标题】:Asp.net Core Razor Pages Post From _layoutAsp.net Core Razor 页面从 _layout 发布
【发布时间】:2020-05-26 04:25:27
【问题描述】:

我想要做的是使用从服务器会话填充为深色或浅色的复选框来更改应用程序的主题。

我知道可以使用 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 em> 到局部视图我得到的视图数据不能为空,虽然模型和视图数据已经设置)并且视图组件不能调用方法。

我应该使用什么方法?

【问题讨论】:

    标签: c# razor-pages asp.net-core-3.1


    【解决方案1】:

    无论您目前身在何处,都可以发布到不同的路线。因此,假设您有一个 Razor 页面 SwitchTheme.cshtml,其中包含在 POST 上切换主题的代码隐藏,那么您可以调整您的 &lt;form&gt; 标签以发布到该页面:

    <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);
        }
    }
    

    【讨论】:

    • RedirectToLocal 在当前上下文中不存在(我找到了 LocalRedirect 代替),@Request.Path 也不存在。我错过了一些进口吗?
    • 对于替代解决方案,您能给我一些示例代码吗?
    • 我的错,是Context.Request.PathLocalRedirect
    • 已修复但未调用操作,是否必须在启动类中添加一些配置?我也尝试将 [Route("api/[controller]")] [ApiController] 添加到 UtilityController 但仍然不起作用
    • 我添加了 services.AddControllersWithViews();到 ConfigureServices 和 endpoints.MapControllers();到配置中的 app.UseEndpoints 现在它可以工作了
    猜你喜欢
    • 2022-01-11
    • 2021-02-04
    • 2018-11-24
    • 2018-07-30
    • 2022-01-19
    • 2020-10-10
    • 2020-08-22
    • 2021-10-27
    • 2019-05-22
    相关资源
    最近更新 更多