I want to create an mvc application, Can I combine mvc controller with razor pages instead of cshtml? Any help tutorial or documentation is welcome. Thanks.
CodePudding user response:
If, when you asked 'Can I combine mvc controller with razor pages instead of cshtml?' you were asking if it's possible to add blazor components to an MVC app, here's how it's done:
Start a new .Net 5.0.402. It MAY work on an earlier version but I haven't tested it.
To your MVC solution, add a blazor web assembly app project. This is the web assembly components project.
On the MVC view, at the place you wish to render your blazor component add:
@using myawesomewasmprojectnamespace.Pages
<component type="typeof(Counter)" render-mode="WebAssemblyPrerendered"/>
<script src="_framework/blazor.webassembly.js"></script>
The '@using
' declaration refers to the blazor web assembly app project, Pages directory. The 'typeof(Counter)
' type refers to the Counter.razor
component in the default blazor web assembly app project, visual studio supplies. This may of course be swapped for the final design component.
In the MVC project's _Layout.cshtml
, or wherever the <head>
tag of the MVC view is, include in the <head>
tag for every page with a blazor component in it:
<base href="/"/>
Add the 'Microsoft.AspNetCore.Components.WebAssembly.Server' package to your MVC project.
Add a reference to the blazor web assembly app project, in your MVC Dependencies, project references.
In the MVC apps Startup.cs, 'public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
' method, add the following:
app.UseBlazorFrameworkFiles();
In the blazor web assembly app project, Program.cs
file, comment out the following line to stop the application looking for a '<div id="app"></div>
'
//builder.RootComponents.Add<App>("#app");
Finally, delete the favicon from the blazor web assembly app project's wwwroot directory as it will clash with the MVC one.
This then adds the 'Counter' component to your MVC view.
To add a different blazor component to a different view, insert it with:
@using myawesomewasmprojectnamespace.Pages
<component type="typeof(Myawsomecomponentnamecompletelydifferentfromanymvccontrolleroractionname)" render-mode="WebAssemblyPrerendered"/>
<script src="_framework/blazor.webassembly.js"></script>
And start your blazor component with:
@page "/myawsomecomponentnamecompletelydifferentfromanymvccontrolleroractionname"