Blazor in .NET 8 | A Complete Overview of the New Features

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to the course new blazer features in net 8 a mini course I'm Ganesh and I'll be your instructor for this course at the end of this course you'll have gained an understanding of the new features of Blazer in net 8 some of the topics that we cover in this course include static server rendering enhanced navigation and form handling streaming rendering adding interactivity on a per component basis I have designed this course for both beginners and experienced developers who want to learn what's new in Blazer in net 8 so thank you and I look forward to seeing you on the other side this course has been updated to use net 8 release candidate 2 which you can download from this URL here and I'm using visual studio 2022 preview 17 .8 which you can download from this URL here and finally make sure you select asp.net and web development workload when installing Visual Studio in this video we talk about the high level goal for Blazer in net 8 but before we do that let's take a step back and discuss how we built web apps in Net 7 first we used static server rendering or serers side rendering to build server rendered web applications with Frameworks like razor pages and MVC in this model the browser sends a request to the server on the server the request is routed to an endpoint such as a razor page and the Razer page executes on the server to dynamically render HTML and that HTML is added to the response and sent back to the client browser and the browser then displays the web page now static server rendering has the following benefits first the app loads faster because all the work is Al already done on the server and the client has to Simply display the HTML second the app can easily access server resources such as databases and finally the site is also easily indexed but there are a few drawbacks too the first is that the cost of processing and memory use are concentrated on the server and the second one is for every user interaction a round trip to the server is required and one issue with Frameworks like razip pis and MC is that they lack a component based programming model for building reusable pieces of web UI so that was static server rendering what if we wanted to build interactive web applications inet 7 well we had the Blazer framework Blazer is a web framework for building web UI components called razor components and these razor components can be hosted in different ways first we have the Blazer server hosting model where the razor components are hosted on the server in an asp.net core application on the client a Blazer script called blazer. server.js establishes a signalr connection with the server and any UI updates event handling and JavaScript interop calls are handled over this signalr connection Blazer server has the following benefits first the app loads faster because the download size is very small second the app can take advantage of server features and the use of net apis and Blazer server can work with thin clients for example browers that don't support web assembly and finally the applications code is not served to clients so it cannot be tampered with blazer server has some drawbacks too first there is some latency involved because every user interaction needs to go to the server second there is no offline support and third server resources are required if you want to scale the app and finally an asp.net course server is needed to serve the app so for example it is not possible to deliver the app from a Content delivery Network next we have the Blazer web assembly hosting model in this model the rer component executes on the client inside the browser on a web assembly based net runtime so here a script called blazer. Web assembly. JS downloads the web assembly based net runtime the required net assemblies and the dependencies from the server and then the application starts executing on the client inside the browser Blazer web has the following benefits first for Standalone Blazer web assembly apps the app is functional even if the server goes offline next the capabilities of the client are fully leveraged and also work is offloaded to the client and finally an asp.net go server is not needed to serve a standalone Blazer web assembly app Blazer web assembly has a few drawbacks too first is the clients need web assembly support and also the app takes longer to load because because code has to be downloaded and executed on the client Net 7 provides us with two main templates for building Blazer apps the first is a Blazer server app template which is used for building Blazer server applications the second is the Blazer web assembly app template which is used for building Blazer web assembly apps so that was Net 7 from what we learned so far we can identify three issues the first is that razip bers and MEC lack a component model the second second is what if we wanted to use static server rendering for the homepage of our site but then add interactivity to individual parts of our site to do this in Net 7 we have to combine multiple Frameworks like razor Pages or MC and Blazer and the final issue is that when we need to build a Blazer app we need to make an upfront decision on which hosting model to use and once we make the decision the entire application will now be either a Blazer server app or a Blazer web assembly app now Blazer and net 8 combines the benefits of Razor Pages MVC and Blazer and provides us with a consistent component-based programming model for building full stack web uis and in order to support this new features are added to Blazer and these are static server rendering and Progressive enhancements such as enhanced navigation and form handling streaming rendering and the ability to add interactivity using Blazer server or Blazer web assmbly on a per component basis all these features are supported with the new blazer web app template so let's talk about that next in this video we're going to talk about the new blazer web app template in net 8 so let's start Visual Studio 2022 preview click create a new project now let's select the new blazer web app template and click next give the project a name say Blazer new features and click next in the framework dropdown we can see we have net8 selected and below that we see we have authentication type that is by default set to none if you click the drop down we also have the individual accounts option this will produce a Blazer based identity UI and set it up for us let's leave it to none and further down we have two more drop downs one for selecting the interactivity type and another for selecting the interactivity location let's see what these do the interactivity type drop- down let's us select which interactive render modes we want to enable for our project with the none option the application will have no interactivity so it will simply use static server rendering without any interactivity either on the server or on the client if we want to enable interactivity on the server using interactive server rendering then we can select the server option or if we want to enable interactivity on the client using interactive client rendering then we can select the web assembly option and if you want to enable both interactive server rendering and interactive client rendering and the ability to switch between them at run time then we can use the auto or the automatic option we'll talk about the different interactive render modes in detail in another video now one thing to note with the web assembly and auto interactivity types an additional client project will be created and added to a solution we'll talk about that later in this video for now set the interactivity type to server the interactivity location drop- down determines where in our app we want to enable interactivity if we select the per page or component option then interactivity will be enabled at the page or the component level so this means that the entire application will use static server rendering and then interactivity will be enabled on a per component basis on the other hand if we select the global option then interactivity will be enabled globally for the entire app so this means that if for example in in the interactivity type drop down we select the server option and in the interactivity location we select Global then it behaves just like a Blazer server app in Net 7 similarly if we select the web assembly interactivity type and Global interactivity location then it behaves just like an asp.net core hosted Blazer web assembly app let's leave the interactivity location set to per page or component and finally if you want to include sample pages and a layout based on bootstrap styling we can leave this checkbox checked and then click create once our project is created go to the program.cs class file this file contains the entry point to our application here we are creating an instance of the as. netcore web application Builder and adding various services to it first we are registering the services required for razor components and since we enabled interactive server rendering in the project template we have this call to add interactive server components this method adds the necessary services to support interactive server rendering then we are calling build on the web application Builder instance which will return an instance of web application and if we scroll down we can see we are configuring the middleware pipeline and finally we are calling app. map Razer components which discovers any available routable razor components and set them up for endpoint routing and for the type argument we specify app which is a root component for our application and add interactive server render mode enables the interactive server render mode for our application and finally we're calling run on the web application instance to start the application now expand the components folder which is where we find all our components and that will click app. Riser this component is a root component for the app it contains the usual HTML markup along with the Head outlet component the routes component and the Blazer web app script which is blazer. web.js the Blazer web app script enables Progressive enhancements for the app such as enhanced navigation and form handling and streaming rendering then we have the routes component this component sets up routing using the Blazer router component next the pages folder contains the apps routable server side razor components first we have counter. Razer which implements the counter page so here at the top of this page we seeing the old way of setting the interactive rendom mode this a Pi has been replaced with at render mode razor directive so we can simply say at render mode render mode. interactive server so this turns on interactive server rendering for this page now render mode is a static class an interactive server and other properties are static properties on this class so instead of prefixing the property with the random mode class we can use a shortcut so go to theore imports. Razer file and use the C using static feature so let's say at using static microsoft. aspet core. components. web. rendom mode so now we can go back to the counter component and remove the rendom mode prefix like so next we have the error page the homepage and the weather page and for the weather page we have an attribute here that turns on a progressive enhancement called streaming rendering now let's expand the layout folder the layout folder contains all the shat components and stylesheets for the apps layout so it contains main layout. Razer so here we have the N menu component and if you scroll down we can see the Blazer error UI here then we have the stylesheet for the main layout component in main layout. razor. CSS then we have nav menu. Riser which implements the navigation menu the style sheet for the na menu component is present in na menu. razor. CSS next we have the app settings. Json file which contains any configuration settings for the project next the www root folder contains public static assets such as bootstrap stylesheets and other CSS files and images and finally the properties folder contains a file called launch settings. Json which holds development environment configuration now let's close Visual Studio click save and start Visual Studio once again click create a new project and select the Blazer web app template and click next and give the project a new name say Blazer new features. net 8 and click next this time let's set interactivity type to Auto and interactivity location to Global and click create as you can see here a client project has been created and added to the solution this is because any components using the interactive web assembly and interactive Auto render mode modes must be built from the client project so if you go to the server project and double click program.cs class file we can see we have the call to add interactive web assembly components which configures the necessary services for enabling interactive client rendering and if you scroll down we have ADD interactive web assembly render mode which configures the interactive web assembly render mode the add additional assemblies method specifies any additional assemblies containing routable razor components that need to be discovered if we expand the components folder and double click app. Razer we can see we are enabling Global interactivity by setting the random mode razor directive attribute for the routes component and for the Head outlet component by setting the rendom mode for the routes component to interactive Auto the Blazer router will have its rendom mode set to interactive Auto which will in turn propagate its rendom mode to all the pages it routes essentially making the entire app interactive now finally in the client project we we have the program.cs class file which contains the startup Logic for this project next we have routes. Razer which contains the Blazer router next the underscore imports. Razer file contains common razor directives such as using directives then the pages folder contains all the routable razor components first we have the counter component next we have the error component but the error component should not be a part of the client project here so if you click build build solution we see we get an error so this is a bug in net 8 rc2 so let's fix this so let's right click this error page and click cut and go to the server project and right click the components folder and click paste now once again click build build solution as you can see the build has succeeded then we have the usual homepage and the weather page and the layout folder contains the layout component which is main layout. Riser its corresponding stylesheet Main layout. rer CSS then we have the namu component and its stylesheet n. razor. CSS and finally the www root folder contains public static assets and the app settings. Json file which contains configuration settings for the client project so that completes our discussion of the Blazer web app project structure next we'll talk about static server rendering in this video we're going to see how static server rendering Works in Blazer in net 8 in static server rendering the browser sends a request to the server on the server the request is routed to a razor component the razor component then executes on the server to produce HTML and that HTML is added to the response and sent back to the client browser the browser then displays the UI let's see how this works in action now for this demo I have opened the Blazer new features solution that I created in the last video and I want want to remove any kind of interactivity for this demo so go to the program.cs class file and remove the call to add interactive server components here and scroll down and remove the call to add interactive server render mode as well now expand the components folder and double click app. Razer and below the routes component we'll find the Blazer web app script which is blazer. web.js now I would like to turn off any Progressive enhancements such as enhanced navigation and form handling and streaming rendering so comment the script out by selecting it and pressing crl KRL C now expand the pages folder and go to the counter component and let's turn off interactivity for this component by removing this razor directive here and also go to the weather component and turn off streaming rendering by removing this attribute here now let's run the app let's open developer tools right click the page click in inspect and go to the network Tab and make sure all is selected here and reload the page and click the counter menu item we see the counter page with the button here and on the right hand side we see the full response coming from the server if we click the Ws tab you see there is no websocket connection that is being initiated by the Blazer web app script or blazer. web.js this means that there is no interactive server rendering using Blazer server by the way these these two connections are initiated by the browser refresh and browser link scripts and not by the Blazer web app script or blazer. web.js which is responsible for establishing a signal R connection for interactive server rendering and if you click the vasm tab we can see there are no assemblies being downloaded either this means that there is no interactivity via interactive client rendering using Blazer web assembly and since there is no interactivity if you click the button on the counter page you see nothing happens this this is because the application is just using static server rendering with no interactivity either on the server or on the client next will progressively enhance the experience by adding support for enhanced navigation and form handling in this video we're going to talk about enhanced navigation and form handling a feature that is introduced to Blazer in net 8 this feature is a progressive enhancement made to static server rendering and it improves the user experience of a web app app so first let's see how static server rendering Works without this feature enabled so here we have a browser that sends a request to the server on the server the request is routed to a razor component the razor component then executes and produces HTML and that HTML is added to the response and sent back to the client browser the browser then displays the web page now there are two problems with this approach first it causes a full page refresh and second for form requests the users scroll position is lost so overall it leads to a poor user experience now let's see how static server rendering with enhanced navigation and form handling works here initially the browser sends a request to the server on the server the request is routed to a razor component the razor component executes on the server using static server rendering and produces HTML and that HTML is added to the response and sent back to the client browser and the browser then displays a web page but now the response contains a script called the Blazer web app script which is blazer. web.js when the user now wants to perform a navigation or submit a form the Blazer web app script or blazer. web.js will intercept that request and perform a fetch request to the server then on the server the request will be routed to a razor component and the Razer component will execute as usual using static server rendering to produce HTML and that HTML will be added to the response and sent back to the client c browser but this time the Blazer web app script will handle that response and it will calculate the minimum number of changes needed to update the Dom and it will patch those changes into the UI and the UI is now updated so with this approach we don't have a full page refresh anymore and for form requests the users's scroll position is also not lost so this improves the user experience of the web app let's see how this works in action for this demo again I have the Blazer new features Sol solution opened up now expand the components folder and double click app. Riser right below the routes component we see the Blazer web app script commented out so this disables any Progressive enhancements such as enhanced navigation and form handling and streaming rendering now if you run the application and go to developer tools just right click anywhere on the page and click inspect and go to the network Tab and make sure all is selected here reload the page and go to the counter component on the right hand side we see the full response coming from the server including all the static assets and everything and if you look at the loading spinner here and navigate to a new component we see there is a small blip this indicates that a full page refresh is occurring whenever we navigate to a new component now let's go back and uncomment the script out so this turns on enhanced navigation by default once again let's run the app right click anywhere on the page and click inspect go to the network Tab and make sure all is selected here and refresh the page and navigate to The Counter component we can see a fetch request was initiated by the Blazer web app script which is blazer. web.js and the counter component executed on the server and the response was returned we can confirm that a full page refresh is not occurring by looking at the loading spinner here again as we navigate to a new new component there's no blip this time now let's go back and go to home. Riser now as I already said enhanced navigation is enabled by default with the Blazer web app script now what if we want to disable enhanced navigation on a perlink basis so let's say we have an anchor tag that links to the counter component and I would like to disable enhanced navigation for this link so to do that we have to use the data enhanced s at rute on the anchor tag and set it to false now once again run the app right click the page click inspect go to the network Tab and make sure all is selected here and refresh the page and click the counter link we can see there is no fch request that is being initiated by Blazer web app script for the counter component instead we get the entire response from the server this is because we have disabled enhanced navigation on the link now enhanced navigation can also be controlled hierarchically so for example if we place the anchor tag inside the div element and set the div elements data enhanced nav attribute to false then enhanced navigation will be disabled for the anchor tag inside that div now let's see a scenario where we want to disable enhanced navigation let's say from a razor component we want to navigate to a non- Blazer endpoint such as a razor page so now go to the program.cs class file and add the required services for razor pages so builder. services. add Razer pages and scroll down and register the endpoints for razor Pages by calling app. map Razer Pages now right click the project and select add new folder and name the folder Pages now right click the pages folder and select add razor page select the razor page empty template and name the razor page test and on this page create a H1 heading with the text this is a test page now from the homepage we want to navigate to this test page so go to home. Riser and remove the data enhanced nav attribute from the dev element and set the HF attribute value of the anchor tag to test and set the link text to Test Now run the app right click the page click inspect and go to the network tab this time select The Preserve log checkbox here and on the homepage click the test link we can see at first a fetch request is being made for the test page then a full page request is being made for the test page and we get the response here this is happening because if the destination is a non- Blazer endpoint such as a Razer page then enhanced navigation does not apply so a second request will be done using a full page load in order to avoid this duplicate request we can disable enhanced navigation for this link so now let's apply the data enhanced nav attribute to the Anchor tag or the dev element and run the app and right click the page click inspect click the network Tab and make sure preserve log is checked and all is selected and click the test link we can see on the right hand side here we don't have the fit request anymore now let's talk about enhanced form handling right below this div create a div element and style it to consume the entire viewport height like so and below that div create a form element with method set to post and form name directive attribute set to my form and inside that form use the anti forgery token component and below that create an input element with name set to my input and finally create a button element with type set to submit and the text as submit now run the app and scroll down and enter some text into the form and click the submit button we see that the scroll position is now lost this indic Ates that a full page refresh occurred and enhanced form handling did not occur this is because for form requests enhanced form handling is an opt-in feature now the reason this decision was made is that if enhanced form handling was by default enabled for a form post and if the form posts to a non- Blazer endpoint such as a Razer page then obviously the initial Fitch request will fail and a second full page request has to be made now doing a duplicate post request may lead to a duplicate transaction on the the server so in order to avoid this the enhanced form handling feature is optin in order to op in to enhanced form handling we can apply the data enhance attribute on the form element like so now if we run the app and scroll down and enter some text into the form and click the submit button we see that the page has not lost its scroll position so this indicates that a full page refresh did not occur so enhanced form handling was being used and by the way if you're using the edit form component to create a form we can use the enhanced component parameter to turn on enhanced form handling for the form now let's talk about the data permanent attribute this attribute can be applied on any element and it simply preserves the content of that element whenever an enhanced navigation occurs let's see how it works under components folder expand the layout folder and double click main layout. Razer now go to to the div with the class top row and replace the anchor element inside it with an empty div element whose ID is set to my Dev now let's set the content of this element using JavaScript so scroll down and create a script element and inside it save VAR element equals document. query selector hash my Dev Now set the inner HTML of the element to div content inside an H1 tag now let's run the app and on the right hand side here we see the text div content but when we navigate to a new component we see that the div content has disappeared Now navigate back to the home component we still don't have the div content here anymore now let's understand why this is happening first of all remember that the content of the dev element is being set client site via JavaScript now when we navigate to a new component using enhanced navigation the component is going to execute on the server to produce HTML and that HTML will be added to the response and sent back to the browser now the Blazer web app script or blazer. web.js looks at the rendered response and sees that the div content is not anywhere in the response now since enhanced navigation applies changes based on the return response from the server it simply discards this div content and that's why the div content has disappeared now in order to preserve the content of this element whenever enhanced navigation occurs we can use the data permanent attribute on the div element like so now run the app we can see the div content is preserved when we navigate to a new component lastly we have the enhanced load event that we can use to listen for enhanced page updates and streaming updates so go to app. Razer and after the Blazer web app script reference create a script element and say blazer. add event listener pass an enhanced load for the first argument and for the second argument pass in a Lambda and call console.log there was an enhanced update now run the app and right click the page click inspect and click the console Tab and navigate to The Counter component we see there was an enhanced update being logged into the console likewise if we do a couple more times we see the number getting incremented let's talk about two more things when we want to do a programmatic navigation we know we can inject an instance of navigation manager and call navigation. navigate to and pass in a URL now we can use a second parameter called Force load which by default is set to false when Force load is false then enhanced navigation will be used for the requested URL if it is available if it do not it will simply do a full page reload we can explicitly set Force load to true and when we do that the navigation will be performed using a full page reload regardless of whether enhanced navigation is available or not and also we can refresh the current Page by calling navigation. refresh it accepts a Boolean parameter called Force reload which again is by default set to false so when it is false the page will be refreshed using enhanced navigation if available and if it is not available the page will be refreshed using a full page reload and we can pass through to the force load parameter so that a full page reload is always performed even if enhanced navigation is available so that covers the basics of enhanced navigation and form handling next we'll talk about another Progressive enhancement called streaming rendering in this video we're going to talk about streaming rendering a feature that is added to Blazer in net 8 streaming rendering ing is a progressive enhancement made to static server rendering that improves the user experience of a web app to understand this let's first see how static server rendering Works without streaming rendering turned on here we have a browser that sends a request to the server on the server the request is routed to a razor component now let's say the razor component wants to perform a long running asynchronous operation this might be for example making a web API call or quering a database for data now in the usual static server rendering scenario the entire operation must complete before the response can be generated and sent to the client browser the browser then displays a web page with all the data now since the response is sent to the browser only after the long running operation completes it causes a significant delay in loading the page leading to a poor user experience now let's see how static server rendering works with streaming rendering turned on now here again the browser sends a request to the server on the server the request is routed to a razor component now the Razer component May perform a long running operation such as quering a database for data and while that is happening the page will be initially rendered to HTML with its layout and some placeholder and that HTML will be added to the response and sent back to the browser the browser then displays the web page with the placeholder now once the asynchronous operation completes on the server the updated data will be streamed into the response that is the updated data will be sent to the client on the same response connection and then on the client it will be patched into the Dom and the UI is now updated with that data the advantage here is that the main layout is rendered as quickly as possible and the page is updated as soon as the data is ready this improves the user experience of the web app let's see this in action for this demo I have the Blazer new features solution opened up and inside app. Razer let me comment the Blazer web app script or blazer. web.js like so so this turns off any Progressive enhancements such as enhanced navigation and form handling and streaming rendering as well now go to the weather component and scroll towards the bottom and let's look at the logic for this page first we have a weather forecast array that will initially be null then in the on initialized async life cycle method we're simulating a long running operation by calling await task. delay for half a second let's change it to 1,000 milliseconds or 1 second until then the forecast variable will be null and after that we are populating the forecasts array with some data if we scroll towards the top we can see we're checking if forecast is null in which case we are showing a loading placeholder and once the long running operation that is simulated by task or delay is complete and data is available we're displaying that data inside the else part here now if we run the application and navigate to the weather component we see that it takes a second to load the entire page this is because the page can be loaded only when the asynchronous operation completes now let's go to app. Razer and uncomment the Blazer web app script like so and go to the weather component and let's enable streaming rendering for this page by using this razor directive at attribute stream rendering passing in through now let's run the app and navigate to the weather component we can see that in ially the UI contains a loading placeholder and once the asynchronous operation completes and data is available the loading placeholder is replaced with the actual data and the page is updated next we'll talk about the different render modes available in Blazer inet 8 in this video we'll talk about the different render modes available in Blazer in net 8 there are four render modes available in Blazer in net 8 we have the static render mode interactive server render mode interactive web assembly render mode and the interactive Auto render mode of these render modes interactive server interactive web assembly and interactive Auto are called interactive render modes let's see how all these render modes work now for this demo I have the Blazer new features. net a solution opened up and before we talk about the various render modes let's revisit the Blazer web app template and see how the template lets us add support for various random modes so click file new project and select the Blazer web app template and click next click next once again now here in the interactivity type drop down we have the following options none server web assembly and auto server and web assembly if you select the none option then the application will be configured to support the static render mode but not other interactive render modes such as interactive server interactive web assembly and interactive Auto if on the other hand we select the server option then the application will support the interactive server render mode similarly if you select the web assembly option the application will support the interactive web assembly random mode now if you select the last option here Auto server and web assembly then the application will support both the interactive server and interactive web assembly render modes but also interactive Auto which provides the ability to switch between interactive server and interactive web assembly at runtime now if you select the web assembly or auto interactivity types then an additional client project will be created and added to the solution in the interactivity location drop-down we have the following options per page or component and Global the interactivity location determines where in our app we want to enable interactivity so for example if we select server in the interactivity type and and per page or component in the interactivity location then the entire application will use the static render mode but then interactivity can be enabled on a per component basis using interactive server render mode similarly if we select the web assembly interactivity type and per page or component in the interactivity location then the entire application will use the static render mode but then interactivity can be enabled on a per component basis using interactive web assembly and finally what if we select server in the interactivity type and Global in the interactivity location this turns on global interactivity for the app so that the entire application will use the interactive server Ender mode so this is similar to a Blazer server app in Net 7 if you select web asmbly in the interactivity type and Global in the interactivity location the entire application will be configured to use interactive web assembly render mode so the app behaves just like an asp.net code hosted Blazer web assembly app in net 7 for the current solution which is Blazer new features. net 8 I had selected Auto for the interactivity type and Global for the interactivity location let's close this dialogue and go to the server project and double click program.cs class file here we can see the call to add interactive server components this adds the necessary services to support rendering interactive server components next we have the call to add interactive web assembly components which adds services necessary to support rendering interactive webs components and if we scroll towards the bottom here we have the call to add interactive server render mode which adds configuration for enabling the interactive server render mode and next we have the call to add interactive web assembly render mode which configures the interactive web assembly render mode and together these two calls also enable the interactive Auto render mode finally we have the call to add additional assemblies method where we are passing in the assembly that the counter type is defined this counter is a razor component that's present in the client project here this project got created because we selected the auto interactivity type in the Blazer web app template now the add additional assemblies method discovers any routable razor components that may be present in the client project assembly now let's showcase these various random modes right click the components folder and create a new folder called pages right click the the pages folder and select add razor component and name the component render modes now at the top of this file specify an at page razor direcor with a route template of/ render Das modes now let's add this page to the navigation menu so go to the client project and expand the layout folder and double click now menu. Razer scroll down and copy the last div with a class nav item and paste it just below replace the HF attribute value of the naving component to render Dash modes and remove the class attribute for the span tag and replace the weather text with blazer render modes now go back to the server project and right click the components folder and select add razor component and name the component show message and create a button element with the text show message and specify and at on click razor directive attribute and set it to handle show message click and specify a class attribute and set it to BTN BTN primary and in the code block below create a private void method handle show message click now when the button is clicked we want to show a message so let's create a private nullable string field called message and inside the event handler set the message to message one and over here at the top inside the heading element use razor syntax to display the value of the message field now go to the render modes component and add the show message component as a child component like so now go to app. Razer and here we can see we are specifying the rendom mode razor dtive attribute for the routes component and for the Head outlet component so this is setting up Global interactivity let's get rid of both so now the routes component will have a default render mode of static if you go to routes. Razer we can see that it's just a wrapper around the Blazer router component so now the router component will have the rendom mode static and the Blazer router will propagate its rendom mode to any page it routes so for example if we navigate to rendom modes page then the rendom modes page will also have the default static rendom mode so let's go to rendom modes. Riser and contains show message as a child component now the show message component will inherit the render mode of its parent component which is static so the show message component will also have the static render mode Let's go to the show message component since this component has a static render mode it uses static server rendering so the component is rendered on the server and there is no interactivity either on the server or on the client so this means that there's no interactive server rendering using Blazer server or interactive client rendering using Blazer web assembly so this means that if you click on the button nothing will happen so let's demonstrate that by running the app now right click the page and click inspect go to the network Tab and make sure all is selected and click the Blazer render modes menu item here and we see that a fch request is being made for the render modes component as a result of enhanced page navigation but if you click the Ws tab here we see that there is no socket connection here this indicates that there is no interactive server rendering using Blazer server and if we click the vasm tab we can see there are no assemblies being downloaded either this means that there is no interactive client rendering using Blazer web assembly and if you click the button on this page we see that the button is not interactive this is because the components render mode is static that means it uses static server rendering and the component is rendered statically on the server with no interactivity either on the server server or on the client now let's add some interactivity we'll first do that by applying a render mode to a component instance let's go to the rendom modes component and for the show message component let's set an at render mode razor directive attribute to rendom mode. interactive server now rendom mode is a static class an interactive server and other properties are static properties on this class so we can take a short cut here and go toore imports. Riser file and use the Cs using static feature and specify at using static microsoft. aspinet core. components. web. render mode now go back to the rendom modes component and remove the rendom mode prefix like so now with the interactive server rendom mode the component is rendered on the server and the component is also interactive so it uses interactive server render rering using the Blazer server hosting model now let's run the app right click the page click inspect Ando to the network Tab and click ws and click the Blazer render modes menu item we see that a websocket connection has been established so this indicates that the component is using interactive server rendering using the Blazer server hosting model and if you click the vasam tab we can see that there are no assemblies being downloaded this means that interactive client rendering using a web assembly is not used and if you click the button here you see that we get the message as the button is interactive now for the next two render modes interactive web assembly and interactive Auto the component needs to be built from the client project so let's right click the show message component in the server project and select cut and right click the client project and select paste now in the rendom modes component instead of interactive server let's say interactive web assembly we with the interactive web assmbly render mode the component is rendered on the client and the component is interactive so the component uses interactive client rendering using Blazer web assembly let's run the app make sure to click build build solution so let's run the app once again and right click the page and click inspect and go to the network Tab and click vasum now and click the Blazer rendom modes menu item we see here on the right hand side a list of assemblies including the web assembly based. net runtime are downloaded to the browser this is because the component is using interactive client rendering using Blazer web assembly and if you click the Ws tab you see there is no websocket connection being made this is because the component is not using interactive server rendering using Blazer server and since the component is interactive if you click the button here we see once again we get the message finally we have the interactive Auto render mode with interactive Auto the component is initially rendered on the server via interactive server rendering using Blazer server and meanwhile in the background the Blazer app bundle and the web assembly based net runtime are downloaded and cached so that it is used on future requests so this means that although the component is rendered initially on the server via interactive server rendering using Blazer server on subsequent visits the component is rendered on the client via interactive client rendering using Blazer web assembly so if you run the app and right click the page and click inspect this time click the double arrow here and click the application Tab and click storage now let's clear any site data click the double arrow once again and click the network Tab and make sure WS is selected here and click the Blazer and the modes menu item we see that we have a websocket connection being established at the same time if we click the vasm tab we see a list of assemblies getting downloaded including the web assembly based. net runtime so this will be used on subsequent visits to the component and again the button is interactive so if we click the button we see the message now from a static pattern component we can pass parameters to an interactive child component but these parameters must be Json serializable so for example I can go to the client project and double click show message. Riser and I can define a public string prop property and decorate it with a parameter attribute to make it a component parameter and over here at the top I can display the value of the message parameter inside a H4 heading and back to the rendom modes component I can set the message component parameter to message two and if you run the app and click on the Blazer render modes menu item we see the message two getting displayed but let's say I go to the show message component and Define a child content property of type render fragment and designate it as a component parameter and then render the child content here at the top and let's go to the render Mod's component and Define some child content within the opening and closing tags of the show message component and run the app and click on the Blazer render modes menu item we get an exception because we are passing render fragment which is arbitrary code and it cannot be calized this is because from a static pattern component we can only pass parameters to an interactive child component that are Json seizable let's undo the changes that we have made now from a static parent component we can have sibling child components with different interactive render modes so for example one show message component can have the interactive server and the mode while another show message component can have the the interactive web assembly rendom mode next we can apply a rendom mode to a component definition so we can say at render mode interactive server or interactive web assembly or interactive Auto but note that if you're designing a component you should avoid coupling the components implementation to a specific rendom mode components should be designed in a rendom mode agnostic manner so we should not make assumptions on where the component is running either on the server or on the client and it should degrade gracefully when rendered statically now there are two scenarios where it is needed to specify a render mode to a component definition the first is when we want to specify a rendom mode for all component instances the second scenario is when the component is not instantiated directly such as with the routable page component in our case now from an interactive parent component we can't switch to a different render mode in an interactive child component so for example at the page level here we have interactive server and the mode in the child component we cannot have interactive web assembly and finally we can set the render mode for the entire app this can be done by going to app. Razer and specifying an at render mode Razer dtive attribute for the routes component and setting it to the desired interactive render mode and doing the same thing for the Head outlet component as well so this sets up Global interactivity for the app now finally pre-rendering is by default enabled for interactive components to disable pre-rendering for a component instance while setting the render mode we can create a new instance of the desired interactive render mode and pass in pre-render false now in order to disable pre-rendering for the component definition we can create a private static field of type I component render mode and initialize it to an instance of the desired interactive render mode passing in pre-render false and over here at the top we can specify the at render mode razor directive and specify the field we just created and finally we can disable pre-rendering for the entire app by going to app. Riser and while setting the rendom mode razor directive attribute we can create an instance of the desired interactive rendom mode and pass in pre-render false and we should also do the same thing on the Head outlet component so that covers the basics of render modes in Blazer next we'll talk about Blazer sections in this video we're going to talk about sections a feature that is added to Blazer in net 8 Blazer sections are used to control the content in a parent razor component from a child component this is done by using two built-in razor components the section Outlet component and the section content component let's see how this works with an example for this demo I have the Blazer new features. net a solution opened up now let's say I want to create a heading on three pages the counter page homepage and the weather page so let's go to the counter page in the client project and create a H3 heading with the text counter page let's copy this markup and paste it in the home page and replace the text with homepage do the same thing for the weather page but this time replace the text with just weather now run the app and we see the heading on each page now let's say we want to display the heading somewhere outside the page for example in the top row here but this div is present in the main layout component so let's take an attempt to render the page text there copy this heading markup and go to the main layout component and inside the div with the class top row replace the anchor tag with the copied markup so paste the markup here now instead of the static weather text let's use razor syntax to display the value of a field called page text in the code block create a private string field called page text now overwrite the life cycle method on parameter set and here we want to get the name of the page so let's go to the top and inject a service called navigation manage and specify navigation and scroll down and create a local variable called page name and set it to navigation. 2bas relative path and pass in navigation. URI using this value we can set the page text like so now if we run the application we see that in the top right corner the current page name is displayed but this approach has an issue and that is what if there are more pages and we want to display the name of the page in the top row div for each page then the if Els logic will increase in order to accommodate more number of pages so let's use Blazer sections to solve this problem let's remove this code block and here we can define a section Outlet component as you can see it's present in microsoft. aspet core. components. sections namespace so we can add that to the Imports file if we want then go back to the main layout component and add a section Outlet component as you can see here the section Outlet component accepts a parameter called section name there's also a parameter called section ID we cannot specify both we can specify only one let's first see how section name works so let's set the section name to page hyphen text now go to the counter page and add a section content component and as you can see here it accepts a section name parameter set it to the one that's set in the section Outlet component which is Page hyphen text let's copy paste this markup Now do the same thing for the homepage specify homepage and lastly for the weather component we just specify weather let's run the app we can see our page text getting updated now one point to note is that multiple section Outlet components can't have the same section name or section ID also if multiple section content components have the same section name then the matching section Outlet component renders the content of the last rendered section content so if you don't want other section content components to match the name of a section Outlet then we can use the section ID parameter to identify a section and for using this an object reference is needed so go to the main layout component and Define an internal static object field called page text and instantiated now scroll to the top and replace the section name parameter with Section ID and set it to the page text field go to the counter page and replace the section name parameter with Section ID and we need to set it to the same field that's present in main layout so import the name space and set it to main layout. page text again you can add the using directive in the Imports file if you want and do the same thing for the homepage and the weather page and run the app we can see that the name of the current page is displayed and that's the Blazer sections feature remember it's used to control content in a parent component from a child component next we'll see how to render razor components outside the context of an HTTP request or asp.net code in this video we're going to see how to render razor components outside of asp.net core normally components are rendered within the context of an HP request so the browser sends a request to the server on the server the request is routed to a razor component and the razor component executes on the server to produce HTML and that HTML is added to the response and sent to the browser now Blazer in. net 8 lets us render razor components outside the context of an hdp request or asp.net core for example we can have a console app that renders a razor component to a HTML fragment M as a string or stream we can then use this HTML fragment to generate email content or static site content or to build a Content templating engine let's now create a console application to demonstrate this feature let's start Visual Studio 2022 preview click new project choose console app from the project templates and click next give the project a name say render razor component and click next make sure net a preview is selected and click create now we need to install two new get packages so right click the project in solution Explorer and click manage net packages click the browse Tab and check this include pre-release checkbox and search for microsoft. aspinet code. components. web new get package make sure it's at version 8.0 and click install now let's install install another new get package called microsoft. extensions. loging once again make sure it's at version 8.0 and click install now let's go to the project file by double clicking the project name here we need to update the project to use the Razer SDK so in the SDK attribute here add the suffix do Razer so we setting the project SDK to microsoft. net. sdk. Razer let's save the file now let's create a razor component right click the project and click add new item name the component render day. Razer this component will show the current day of week so create a top level heading H1 with the text today is and below that create a H3 element and inside that use the razor syntax to evaluate a cop expression so use at dat time.now day of week and save the file and now let's go to the program.cs class file where we'll write the logic to render the razor component to HTML in order to do that we need to use HTML renderer that is present in microsoft. aspet core. components. webn namespace if you go to the definition of the class we can see that it provides a mechanism for rendering razor components as HTML markup its Constructor takes two parameters m one I service provider and another I logger Factory so first let's set up dependency injection we'll create a new instance of service collection bring microsoft. extensions. dependency injection namespace in and call services. add loging and then create an instance of I service provider by calling services. build service provider and create an instance of ilogger Factory from the service provider by calling service provider. get required service of ilogger factory then create an instance of HTML renderer like so passing in the service provider and logger Factory now we can render a razor component by calling render component async on the HTML renderer but that call should be made in the context of calling invoc casnc on a component dispatcher so let's say VAR HTML equals AIT HTML renderer do dispatcher do invoc casing and pass in an Asing Lambda expression and inside that we can say V output equals AIT HTML render do render component async passing in the type of the component as a generic type argument make sure we include the name space and as a argument to the method pass in parameter view. mty and again we need the names space microsoft. aspinet code. components then let's return output. 2 HTML string and let's end that with a semicolon and finally let's call console. right line passing in the HTML we just created now let's run our application we can see our rendered markup on the current day hi everyone and thank you for taking my course I hope you found the material informative and helpful in this course we covered a lot of ground including static server rendering enhanced navigation and form handling streaming rendering and adding interactivity on a per component basis we also learned how to use Blazer sections and how to render razor components outside the context of an HTTP request or asp.net core thank you again for taking my course I hope you enjoyed it
Info
Channel: CodeGanesh
Views: 3,696
Rating: undefined out of 5
Keywords: Blazor in .NET 8, blazor complete overview, blazor overview, blazor new features, blazor .net 8, blazor latest features, blazor web app template, blazor web app, blazor tutorial, static server rendering, progressive enhancements, enhanced navigation and form handling, streaming rendering, adding interactivity to a page, adding interactivity to a component, render modes, blazor render modes, blazor interactive render modes, blazor sections, render razor components, codeganesh
Id: rmgFSVIc8OM
Channel Id: undefined
Length: 65min 54sec (3954 seconds)
Published: Sun Oct 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.