SiteViewModel.cs

70 lines | 2.313 kB Blame History Raw Download
namespace Web.ViewModels
{
    using DotVVM.Framework.ViewModel;
    using System.Web;
    using System;

    public class SiteViewModel : DotvvmViewModelBase
    {
        #region Toastr Wrappers 
        public void ToastrError(string message, bool isSticky = false, string title = "")
        {
            ShowToast(ToastType.Error, message, title, isSticky);
        }

        public void ToastrInformation(string message, bool isSticky = false, string title = "")
        {
            ShowToast(ToastType.Info, message, title, isSticky);
        }

        public void ToastrSuccess(string message, bool isSticky = false, string title = "")
        {
            ShowToast(ToastType.Success, message, title, isSticky);
        }

        public void ToastrWarning(string message, bool isSticky = false, string title = "")
        {
            ShowToast(ToastType.Warning, message, title, isSticky);
        }
        #endregion

        #region Private Methods
        private void ShowToast(ToastType type, string message, string title, bool isSticky)
        {
            if (String.IsNullOrWhiteSpace(message))
                return;

            var encodedMessage = HttpUtility.HtmlEncode(message);
            var encodedTitle = HttpUtility.HtmlEncode(title);


            string javascript;
            switch (type)
            {
                case ToastType.Error:
                    javascript = $"toastr.error('{encodedMessage}', '{encodedTitle}')";
                    break;
                case ToastType.Info:
                    javascript = $"toastr.info('{encodedMessage}', '{encodedTitle}')";
                    break;
                case ToastType.Success:
                    javascript = $"toastr.success('{encodedMessage}', '{encodedTitle}')";
                    break;
                case ToastType.Warning:
                    javascript = $"toastr.warning('{encodedMessage}', '{encodedTitle}')";
                    break;
                default:
                    javascript = $"toastr.info('{encodedMessage}', '{encodedTitle}')";
                    break;
            }

            Context.ResourceManager.AddStartupScript(isSticky
                ? "Toast.setSticky()"
                : "Toast.setStandard()");

            Context.ResourceManager.AddStartupScript(javascript);
        }
        #endregion
    }
}