hk1980
hk1980

Reputation: 115

ASP.Net Core 3.1 and global view method

The code @await Html.PartialAsync("~/Views/Shared/_Toast.cshtml", new ToastMessage() { Caption = "Hello", Message = "World" }) renders a partial view with arguments. It shows a Bootstrap toast message, which I intend to use everywhere.

Now is it possible to reduce that line to something like @MyHelpers.ShowToastMessage(new ToastMessage() { Caption = "Hello", Message = "World" })? I don't want to use View Components (overkill). Also @functions block seems to be local only.

Upvotes: 0

Views: 219

Answers (1)

Yinqiu
Yinqiu

Reputation: 7180

You can custom a htmlhelper in your app.

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

In your view:

@using App.Helpers


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

@Html.ShowToastMessage(new ToastMessage() { Caption = "Hello", Message = "World" })

If your _Toast.cshtml contains other html elements, then you can use TagBuilder Class to create.

Upvotes: 1

Related Questions