InertiaCore

repository·main·Indexed 41 days ago

https://github.com/kapi2289/inertiacore

An ASP.NET Core adapter for Inertia.js that enables building single-page applications (SPAs) using server-side routing and controllers with frontend frameworks like Vue or React. Features include support for Server-Side Rendering (SSR), async lazy props, global data sharing via Inertia.Share, and a Vite helper for asset management.

Tokens
1.9K
Snippets
11
Records
11
Agent score
50%

What's inside InertiaCore

  1. Handle Form Submissions with JSON

    main

    Because Inertia sends request data as JSON, you must decorate your model parameters with [FromBody] in your controller actions. Validation errors are automatically passed back to the frontend by the adapter.

    [HttpPost]
    public async Task<IActionResult> Create([FromBody] Post post)
    {
        if (!ModelState.IsValid)
        {
            // The validation errors are passed automatically.
            return await Index();
        }
        
        _context.Add(post);
        await _context.SaveChangesAsync();
        
        return RedirectToAction("Index");
    }
  2. Enable Server-Side Rendering (SSR)

    main

    To enable SSR, you must perform two steps:

    1. Configure the Inertia options in Program.cs with SsrEnabled = true and provide the SsrUrl.
    2. Add @await Inertia.Head(Model) to your layout's <head> section.
    // 1. Configuration
    bulider.Services.AddInertia(options =>
    {
        options.SsrEnabled = true;
        options.SsrUrl = "http://127.0.0.1:13714/render"; // default
    });
    @* 2. Layout usage *@
    @using InertiaCore
    <head>
        <title inertia>My App</title>
        @await Inertia.Head(Model)
    </head>
  3. Install AspNetCore.InertiaCore

    main

    You can install the Inertia.js ASP.NET adapter using either the NuGet Package Manager or the .NET CLI.

    # Using .NET CLI
    dotnet add package AspNetCore.InertiaCore
    
    # Using Package Manager
    PM> Install-Package AspNetCore.InertiaCore
  4. Set up the Frontend Root View

    main

    Create a root view file (e.g., /Views/App.cshtml) to serve as the entry point for your Inertia application. Use @await Inertia.Html(Model) to render the initial page content.

    @using InertiaCore
    <!DOCTYPE html>
    <html
        <head>
            <meta charset="utf-8"/>
            <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
            <title inertia>My App</title>
        </head>
        <body>
            @await Inertia.Html(Model)
            <script src="/js/app.js"></script>
        </body>
    </html>
  5. Configure the Root View path

    main

    By default, Inertia uses a standard root view. You can customize this path during service registration using the RootView option.

    bulider.Services.AddInertia(options =>
    {
        options.RootView = "~/Views/Main.cshtml";
    });
  6. Configure the Vite Helper

    main

    The Vite helper allows you to automatically load assets. Register it in Program.cs using AddViteHelper(). You can customize the directory paths via the options object.

    using InertiaCore.Extensions;
    
    // Default configuration
    bulider.Services.AddViteHelper();
    
    // Custom configuration
    bulider.Services.AddViteHelper(options =>
    {
        options.PublicDirectory = "wwwroot";
        options.BuildDirectory = "build";
        options.HotFile = "hot";
        options.ManifestFilename = "manifest.json";
    });
  7. Render pages from the Backend

    main

    Use Inertia.Render(componentName, data) in your controllers to pass data to a specific frontend component. The componentName should match the name of your Vue or React component.

    public async Task<IActionResult> Index()
    {
        var posts = await _context.Posts.ToListAsync();
        
        var data = new
        {
            Posts = posts,
        };
        
        return Inertia.Render("Posts", data);
    }
  8. Use Async Lazy Props for deferred data loading

    main

    To avoid blocking the initial page load with heavy data, use LazyProp. Pass an asynchronous function to LazyProp, and the data will be loaded asynchronously by the frontend.

    public async Task<IActionResult> Index()
    {
        // Data is wrapped in a LazyProp with an async function
        var posts = new LazyProp(async () => await _context.Posts.ToListAsync());
        
        var data = new
        {
            Posts = posts,
        };
        
        return Inertia.Render("Posts", data);
    }
  9. Share data globally using Inertia.Share

    main

    You can share data across all Inertia components (e.g., authentication state) by using Inertia.Share within middleware.

    using InertiaCore;
    
    app.Use(async (context, next) =>
    {
        var userId = context.Session.GetInt32("userId");
        
        // Share as an object
        Inertia.Share("auth", new
        {
            UserId = userId
        });
        
        // Or share using a dictionary
        Inertia.Share(new Dictionary<string, object?>
        {
            ["auth"] => new
            {
                UserId = userId
            }
        });
        
        await next();
    });
  10. Use Vite helpers in Razor views

    main

    Use @Vite.Input("path/to/file") to load scripts or styles. For React applications requiring Hot Module Replacement (HMR), you must call @Vite.ReactRefresh() before @await Inertia.Html(Model) in your layout.

    @using InertiaCore
    @using InertiaCore.Utils
    <!DOCTYPE html>
    <html>
      <head>
        <title inertia>My App</title>
      </head>
      <body>
        @* Required for React HMR *@
        @Vite.ReactRefresh()
        
        @await Inertia.Html(Model)
        
        @* Load your entry point *@
        @Vite.Input("src/main.tsx")
      </body>
    </html>