最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

每日动态!Blazor 使用代码直接在新窗口打开链接, 获取窗口宽度, 使用cookie

来源:博客园


(相关资料图)

1. 在新窗口打开链接

[Inject, NotNull] IJSRuntime? JS { get; set; }

await JS.InvokeVoidAsync("eval", @"let discard= open(https://www.blazor.zone/tables/edit, _blank)");

await JS.InvokeVoidAsync("eval", $"let discard= open({url}, _blank)");

2. 直接获取窗口宽度,不用写js脚本了吧?

var innerWidth = await JS.InvokeAsync("eval", "window.innerWidth");

3. 使用cookie

原文链接: https://www.frankslowcodeblog.com/post/2023/03/23/session-variable-as-cookie-in-radzen-blazor

定义一个服务类:

using Microsoft.JSInterop;namespace MyProject.Utils{    public interface ICookie    {        public Task SetValue(string key, string value, int? days = null);        public Task GetValue(string key, string def = "");    }    public class CookieService: ICookie    {        readonly IJSRuntime JSRuntime;        string expires = "";        public Cookie(IJSRuntime jsRuntime)        {            JSRuntime = jsRuntime;            ExpireDays = 300;        }        public async Task SetValue(string key, string value, int? days = null)        {            var curExp = (days != null) ? (days > 0 ? DateToUTC(days.Value) : "") : expires;            await SetCookie($"{key}={value}; expires={curExp}; path=/");        }        public async Task GetValue(string key, string def = "")        {            var cValue = await GetCookie();            if (string.IsNullOrEmpty(cValue)) return def;                            var vals = cValue.Split(";");            foreach (var val in vals)                if(!string.IsNullOrEmpty(val) && val.IndexOf("=") > 0)                    if(val.Substring(0, val.IndexOf("=")).Trim().Equals(key, StringComparison.OrdinalIgnoreCase))                        return val.Substring(val.IndexOf("=") + 1);            return def;        }        private async Task SetCookie(string value)        {            await JSRuntime.InvokeVoidAsync("eval", $"document.cookie = \"{value}\"");        }        private async Task GetCookie()        {            return await JSRuntime.InvokeAsync("eval", $"document.cookie");        }        public int ExpireDays        {            set => expires = DateToUTC(value);        }        private static string DateToUTC(int days) => DateTime.Now.AddDays(days).ToUniversalTime().ToString("R");    }}

然后在 startup.cs 中添加此服务

services.AddScoped(); 

在页面上使用

[Inject, NotNull] protected ICookie? Cookie { get; set; }await Cookie.SetValue("mytest20", "Hello Blazor!");_message = await Cookie.GetValue("mytest20");

关键词: