【问题标题】:ASP.Net Core 3.1 and global view methodASP.Net Core 3.1 和全局视图方法
【发布时间】:2021-07-16 21:36:39
【问题描述】:

代码@await Html.PartialAsync("~/Views/Shared/_Toast.cshtml", new ToastMessage() { Caption = "Hello", Message = "World" }) 呈现带有参数的局部视图。它显示了一条 Bootstrap toast 消息,我打算在任何地方使用它。

现在可以将该行简化为@MyHelpers.ShowToastMessage(new ToastMessage() { Caption = "Hello", Message = "World" }) 之类的内容吗?我不想使用视图组件(矫枉过正)。 @functions 块似乎也只是本地的。

【问题讨论】:

    标签: asp.net-core-mvc partial-views html-helper


    【解决方案1】:

    您可以在您的应用中自定义一个 htmlhelper。

    namespace App.Helpers
    {
        public static class HtmlHelperExtensions
        {
            public static IHtmlContent ShowToastMessage(this IHtmlHelper htmlHelper, ToastMessage model)
            {
                string str = "<div> "+ model.Caption + " " + model.Message + " <div/>";            
                return new HtmlString(str);
            }
        }
    }
    

    在你看来:

    @using App.Helpers
    
    
    @await Html.PartialAsync("~/Views/Shared/_Toast.cshtml", new ToastMessage() { Caption = "Hello", Message = "World" })
    
    @Html.ShowToastMessage(new ToastMessage() { Caption = "Hello", Message = "World" })
    

    如果你的_Toast.cshtml包含其他html元素,那么你可以使用TagBuilder Class来创建。

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2020-07-06
      相关资源
      最近更新 更多