Blazor در دات نت 7 به همراه امکانات مدیریت بهتر تغییرات آدرس صفحات است. برای مثال توسط آن میتوان به کاربران در مورد کارهای ذخیره نشده، در صورت شروع به هدایت به صفحهای دیگر، هشدار داد.
برای مدیریت تغییرات آدرس صفحات، میتوان از سرویس NavigationManager و متد RegisterLocationChangingHandler آن به صورت زیر استفاده کرد:
var registration = NavigationManager.RegisterLocationChangingHandler(async cxt => { if (cxt.TargetLocation.EndsWith("counter")) { cxt.PreventNavigation(); } });
- خروجی این متد برای مثال registration در اینجا، از نوع IDisposable است و dispose آن سبب حذف Handler ثبت شده میشود.
- باید بخاطر داشت که امکانات فوق تنها آدرسهای درون برنامهای را مدیریت میکند. برای مدیریت هدایت به آدرسهای خارجی باید از رخداد beforeunload جاوا اسکریپت استفاده کرد.
ساده سازی کار با سرویس مدیریت تغییرات آدرس با کامپوننت جدید NavigationLock
نکات عنوان شده را توسط کامپوننت جدید NavigationLock نیز میتوان به نحو سادهتری مدیریت کرد:
<NavigationLock OnBeforeInternalNavigation="ConfirmNavigation" ConfirmExternalNavigation />
از این کامپوننت میتوان جهت مدیریت یک فرم ذخیره نشده درصورت شروع به هدایت کاربر به آدرسی دیگر، به صورت زیر استفاده کرد:
<EditForm EditContext="editContext" OnValidSubmit="Submit"> ... </EditForm> <NavigationLock OnBeforeInternalNavigation="ConfirmNavigation" ConfirmExternalNavigation /> @code { private readonly EditContext editContext; ... // Called only for internal navigations. // External navigations will trigger a browser specific prompt. async Task ConfirmNavigation(LocationChangingContext context) { if (editContext.IsModified()) { var isConfirmed = await JS.InvokeAsync<bool>("window.confirm", "Are you sure you want to leave this page?"); if (!isConfirmed) { context.PreventNavigation(); } } } }
- با استفاده از EditContext یک EditForm و متد IsModified آن میتوان تشخیص داد که اطلاعات فرم جاری توسط کاربر تغییر کردهاست و هنوز ذخیره شده یا نشده.
- در اینجا پیاده سازی OnBeforeInternalNavigation را توسط متد ConfirmNavigation مشاهده میکنید که در آن بررسی میشود آیا کاربر فرم را تغییر دادهاست یا خیر؟ اگر بله، متد confirm جاوا اسکریپت را جهت تائید ترک صفحه نمایش میدهد. اگر کاربر آنرا تائید نکند، توسط متد PreventNavigation، مانع تغییر آدرس صفحه و از دست رفتن اطلاعات خواهد شد.