Share
Explore

Starter code for a beginner-friendly C# web application

Lecture: Building a Simple C# Web Application with ASP.NET Core

Introduction to Web Applications in C#

Web applications are software solutions that are accessible through a web browser over a network, such as the internet or an intranet. C# web applications often utilize the ASP.NET Core framework, which is an open-source, high-performance framework for building modern, cloud-based, internet-connected applications.
Activity A: Hand code an HTML Page; Use VSC; use VSC’s Live Server to view our page
Start VSC → Make a simple static HTML Project
Activity B: Use C# to dynamically generate HTML
Building the simple web application with C#
Microsoft Technology Stack is : ASP .NET
Active Server Pages is the library of Code Classes we use
.Net = the technology Platform
Tools: Visual Studio Code
Microsoft Web Server
Database
ASP.NET Core is designed to allow developers to build web applications and services, IoT apps, and mobile backends.
When you build a web application, you typically develop:
A server-side application <CONTROLLER> that handles HTTP requests, performs operations (such as data access), and generates responses (usually HTML to be rendered by a browser).
Client-side assets that may include HTML, CSS, and JavaScript, allowing users to interact with the application through a web browser.
In this Lab, we'll focus on setting up a simple server-side C# web application that responds with "Hello World".

Prerequisites

To follow along, you should have:
Visual Studio Code installed.
The C# extension for Visual Studio Code.
The .NET 6 SDK or later installed on your system.

Step-by-Step Instructions

Step 1: Create a New Project

Open Visual Studio Code, then open the integrated terminal by pressing `Ctrl + ``. In the terminal, run the following command to create a new ASP.NET Core Web Application:
dotnet new web -o HelloWorldWebApp

This command creates a new folder named HelloWorldWebApp with a simple project for a web application.

Step 2: Explore the Project Structure

Navigate to the project folder in Visual Studio Code by opening the folder:
cd HelloWorldWebApp
code .
Here's a brief overview of what each file and folder is for:
Program.cs:
This is the entry point for the ASP.NET Core application.
It sets up the web host and starts listening for incoming HTTP requests.
wwwroot/: This directory contains static files like HTML, CSS, JavaScript, and images.
appsettings.json: This file contains configuration settings for the application, like connection strings or application settings. (for example: Connection details to your Database)

Step 3: Understand the Code

Open the Program.cs file. You'll see code similar to this:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

Here's what's happening:
WebApplication.CreateBuilder(args): Sets up the necessary configurations and defaults for our app.
builder.Build(): Builds the web application.
app.MapGet("/", () => "Hello World!"): Maps the root URL (/) to a GET request, responding with "Hello World!".
app.Run(): Starts the web server and begins listening for incoming HTTP requests.

Step 4: Run the Application

change directory: cd into your Project Folder

PS C:\lab_NOV03_csharp> cd HelloWorldWebApp
PS C:\lab_NOV03_csharp> dotnet run
PS C:\lab_NOV03_csharp\HelloWorldWebApp> dotnet run Building... info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5134 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Development info: Microsoft.Hosting.Lifetime[0] Content root path: C:\lab_NOV03_csharp\HelloWorldWebApp
In the terminal, run the application with:

dotnet run

Once the application starts, it will listen on a specific port (usually http://localhost:5000 and https://localhost:5001).

Step 5: Access the Application

image.png
Open a web browser and navigate to http://localhost:xxxx. You should see the text "Hello World!" displayed. Where xxxx = Whatever port your application is reporting itself as running on.

Foundations and Fundamentals

When your browser sends a request to the server, here's what happens behind the scenes in an ASP.NET Core application:
The web server (Kestrel, by default) receives the HTTP request.
The request is then processed by the ASP.NET Core middleware pipeline which is configured in Program.cs.
The MapGet method matches the request path to the corresponding delegate (the lambda () => "Hello World!" in this case).
The response is sent back to the browser, completing the HTTP request/response cycle.
This is the fundamental flow of a web application built with ASP.NET Core. Of course, real-world applications are more complex, involving:
routing,
data models,
views,
user authentication
other details needed to make an ecommerce web application work.

Visual Studio Code and C#

Visual Studio Code, coupled with the C# extension, provides a lightweight but powerful environment to build C# web applications.
You get features like IntelliSense, debugging, and task running to streamline your development process.

Conclusion

In this lecture, you've learned what a C# web application is, what pieces it consists of, how to use Visual Studio Code to build it, and the fundamental concepts of how a web application works in ASP.NET Core.
The example we built was a minimalistic web application that serves a "Hello World" message.
For a beginner, this should serve as a launching pad into the world of C# web development. From here, you can explore how to build more interactive and data-driven web applications using the ASP.NET Core framework.

Next Steps:

Build a simple calculator to demonstrate round-tripping between Web Browser and Server. The server will implement some simple logic like adding numbers.
Layer in a Database to achieve persistance.
Implement multiple pages and navigation between the pages.
``` // ASP.NET Core Web Application using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; // Define the ASP.NET Core Web Application public class Startup { // ConfigureServices method - defines the services used by the application public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } // Configure method - configures the HTTP request pipeline public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}"); }); } } // Home Controller using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { // Index action - returns the index view [HttpGet] public IActionResult Index() { return View(); } // Calculate action - performs the arithmetic operation and returns the result [HttpPost] public IActionResult Calculate(string num1, string num2, string op, bool add, bool subtract, bool multiply, bool divide) { double num1Double = double.Parse(num1); double num2Double = double.Parse(num2); double result; if (add) { result = num1Double + num2Double; } else if (subtract) { result = num1Double - num2Double; } else if (multiply) { result = num1Double * num2Double; } else if (divide) { result = num1Double / num2Double; } else { result = 0; } return View("Index", new { result }); } }
// Index view <!DOCTYPE html> <html> <head> <title>Calculator</title> </head> <body> <h1>Calculator</h1> <form method="post"> <label for="num1">Number 1:</label> <input type="text" name="num1" id="num1" /> <br /> <label for="num2">Number 2:</label> <input type="text" name="num2" id="num2" /> <br /> <label for="op">Operator:</label> <select name="op" id="op"> <option value="add">+</option> <option value="subtract">-</option> <option value="multiply">*</option> <option value="divide">/</option> </select> <br /> <input type="submit" value="Calculate" /> </form> <p id="result"></p> </body> </html> ``` This code creates a simple web application that allows the user to enter two numbers and select an arithmetic operation. When the "Calculate" button is clicked, the

Instructional Lab Book: Building a Simple Calculator Web Application in ASP.NET Core using Visual Studio Code

Objective:

By the end of this lab, students should be able to:
Set up a .NET Core web application project in Visual Studio Code.
Understand the structure of an ASP.NET Core Razor Pages application.
Implement a basic calculator using HTML and C#.

Prerequisites:

Visual Studio Code installed.
.NET SDK installed.
C# extension for Visual Studio Code installed.

Step 1: Setting up the Development Environment

Launch Visual Studio Code.
Go to Extensions or press Ctrl+Shift+X.
Search for C# and install the official C# extension by Microsoft.
Restart Visual Studio Code.

Step 2: Creating a New ASP.NET Core Web Application

Open the terminal in Visual Studio Code (View > Terminal).
Navigate to the directory where you want to create your new project.
Create a new Razor Pages web application:
bashCopy code
dotnet new webapp -n SimpleCalculator

Once created, navigate into the project directory:
bashCopy code
cd SimpleCalculator

Open this directory in Visual Studio Code:
bashCopy code
code .

Step 3: Building the Calculator Interface

In the Explorer pane, expand the Pages directory.
Double-click Index.cshtml to open it.
Replace its content with the previously provided HTML code (from the previous response).

Step 4: Implementing Calculator Logic

Now, open the Index.cshtml.cs file (this is the code-behind for our main page).
Replace its content with the provided C# code (from the previous response).

Step 5: Running the Application

In the terminal (within Visual Studio Code), ensure you're in the SimpleCalculator directory.
Run the application using the command:
bashCopy code
dotnet run

Once it's running, you should see a message saying the application has started. Open a browser and navigate to https://localhost:5001 or http://localhost:5000 to access the web application.

Step 6: Testing the Calculator

Input two numbers into the provided fields.
Select an arithmetic operation from the dropdown.
Click the 'Calculate' button and observe the result.
Try various numbers and operations to ensure everything works as expected.

Additional Exercises:

Error Handling: Implement better error handling, e.g., when a user tries to divide by zero.
Styling: Use CSS to enhance the appearance of the calculator.
Additional Features: Add more features, like a history of calculations or the ability to use more advanced operations (e.g., square root, power, etc.).

Conclusion:

Congratulations! You've successfully built a simple web calculator using ASP.NET Core in Visual Studio Code. This lab provided a foundational experience with web development in .NET, and there's a vast ecosystem to explore further as you continue your learning journey.

Let's start by setting up a basic C# web application using ASP.NET Core.

1. Setting up the Project:

First, ensure you have the .NET SDK installed. If not, download it from the official Microsoft website.
Now, create a new web application:
bashCopy code
dotnet new webapp -n SimpleCalculator

Navigate to the project directory:
bashCopy code
cd SimpleCalculator

2. Implementing the Calculator:

a. Modify Pages/Index.cshtml:

This is the main page that will be served:
htmlCopy code
@page
@model IndexModel
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<form method="post">
<input type="number" name="num1" required />
<select name="operation">
<option value="add">+</option>
<option value="subtract">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
</select>
<input type="number" name="num2" required />
<button type="submit">Calculate</button>
</form>
@if(Model.Result.HasValue)
{
<h2>Result: @Model.Result</h2>
}
</body>
</html>

b. Modify Pages/Index.cshtml.cs:

This is the code-behind for the main page and will contain the logic for the calculator:
csharpCopy code
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc;

namespace SimpleCalculator.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public double Num1 { get; set; }

[BindProperty]
public double Num2 { get; set; }

[BindProperty]
public string Operation { get; set; }

public double? Result { get; set; }

public void OnPost()
{
switch (Operation)
{
case "add":
Result = Num1 + Num2;
break;
case "subtract":
Result = Num1 - Num2;
break;
case "multiply":
Result = Num1 * Num2;
break;
case "divide":
if (Num2 != 0)
{
Result = Num1 / Num2;
}
else
{
// Handle division by zero
Result = null;
}
break;
}
}
}
}

3. Run the Application:

In your terminal or command prompt, navigate to the root of your project (SimpleCalculator) and run:
bashCopy code
dotnet run

Navigate to https://localhost:5001 in your web browser. You should see a basic calculator that allows you to perform the specified arithmetic operations.
Please note that this is a very basic implementation meant for teaching purposes. There are more advanced methods and best practices that can be employed for more complex applications. Make sure to test the application and potentially add error handling or other enhancements as needed.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.