I've found a single-page MVC app usually contains more than single-page, and most websites are more than 1 page.
A single-page web app can contain
-
One or more css pages - these pages provide a way to store the formatting for multiple pages in one external file.
-
Several js and lib pages
-
A HomeController.cs
-
A Model.cs - a regular C# class that stores a model of the data for a page.
-
A HomeIndex.cshtml - a Razor page.
-
A Shared _Layout.cshtml - this file stores HTML elements that are common to all pages. It's a great way to cut down coding.
-
Maybe a _ViewImports.cshtml - a Razor page that makes it easier to work with models and tag helpers.
-
Perhaps a _ViewStart,cshtml
-
An appsettings.json page - a great place to hold the connection string if connecting to a data server such as SQL.
-
A program.cs page - this file sets up the app, including defining the Startup.cs file.
-
And finally a startup.cs page - contains the code that configures the middleware for the HTTP request pipeline.
I'm going to start with the controller, which is a C# class that inherits from the Controller class that's available from MS.AspNetCore.Mvc namespace.
​
Most controllers have a method that runs in response to HTTP action verbs such as GET or POST. For example, the Index method (which is highlighted) from a GET is setting a ViewBag property to 0, then returns a View result.
​
As pages get larger then I try to stay away from using ViewBag, but for smaller websites it's usually fine to use sparingly.
​
Next I'll discuss the Razor View.
-
A Razor view contains both C# and HTML. That's why it's file extension is .cshtml.
-
In Core MVC, the Razor view engine user server-side code to embed C# code.
-
To execute one or more C# statements, I can declare a Razor code block by coding the @ sign followed by a pair of curly braces {}.
-
To evaluate a C# expression and display its result, I can code a Razor expression by coding the @ sign and then coding the expression.
using FutureValue.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
namespace FutureValue.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
ViewBag.FV = 0;
return View();
}
​
[HttpPost]
public IActionResult Index(FutureValueModel model)
{
if (ModelState.IsValid)
{
ViewBag.FV = model.CalculateFutureValue();
}
else
{
ViewBag.FV = 0;
}
return View(model);
}
}
}
A Razor view contains both C# and HTML code, which is where the file extension comes from.
The @model tells me this a strongly typed view from the model, FutureValueModel.
​
This code setup the POST back method using a Submit button.
@model FutureValueModel
@{
ViewBag.Title = "Future Value Calculator";
}
<div class="row">
<div class="col offest-sm-3 pl-0">
<button type="submit" class="btn btn- primary>Calculate</button>
<a asp-action="Index" class="btn btn-outline-secondary">Clear</a>
</div>
</div>