Online Doctor Appointment Booking in ASP.NET MVC
A Comprehensive Guide with Code Examples for Form, Payment, and Receipt Download
Highlights
- Integrated System Architecture: Covers appointment booking, payment processing, and receipt generation.
- Step-by-Step Implementation: Detailed models, views, controllers, and integration with payment gateways.
- Practical Code Examples: Ready-to-use ASP.NET MVC code that can be adapted to real-world requirements.
System Overview
This guide describes the creation of an online doctor appointment booking system using ASP.NET MVC. The system comprises three key parts:
- Appointment Booking Form – for patients to select a doctor, choose a date/time, and provide personal details.
- Payment Process Page – integrates a payment gateway (such as Stripe or PayPal) to process the payment for the appointment.
- Success Page with Downloadable Receipt – confirms the successful booking with a downloadable receipt in PDF format.
The implementation leverages ASP.NET MVC’s Model-View-Controller architecture, with models representing system entities, views for the user interface, and controllers handling the business logic. Payment integration is demonstrated using the Stripe API.
Step 1: Setting Up Your ASP.NET MVC Project
Begin by creating a new ASP.NET MVC project in Visual Studio. Include necessary references such as Entity Framework for database interaction and install any required NuGet packages (e.g., the Stripe.net package for payment processing).
Models Creation
Define models for the appointment, payment, receipt, doctor, and patient information. The following sample models illustrate the data structure used in the system.
AppointmentModel
// Models/AppointmentModel.cs
public class AppointmentModel
{
public int Id { get; set; }
public int DoctorId { get; set; }
public DateTime AppointmentDate { get; set; }
public TimeSpan AppointmentTime { get; set; }
public string PatientName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public decimal Fee { get; set; }
}
PaymentModel
// Models/PaymentModel.cs
public class PaymentModel
{
public int Id { get; set; }
public int AppointmentId { get; set; }
public decimal Amount { get; set; }
public string Status { get; set; }
}
ReceiptModel
// Models/ReceiptModel.cs
public class ReceiptModel
{
public DateTime AppointmentDate { get; set; }
public string DoctorName { get; set; }
public string PatientName { get; set; }
public decimal AmountPaid { get; set; }
}
Step 2: Building the Views
The system comprises three key views: the Appointment Booking Form, the Payment Process Page, and the Success Page with receipt download options.
Appointment Booking Form
This view collects the necessary booking information from the patient.
// Views/Home/BookAppointment.cshtml
@model YourProject.Models.AppointmentModel
@using (Html.BeginForm("BookAppointment", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Book an Appointment</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.DoctorId, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.DoctorId, ViewBag.Doctors as SelectList, "Select Doctor", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DoctorId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.AppointmentDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.AppointmentDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
@Html.ValidationMessageFor(model => model.AppointmentDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.AppointmentTime, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.AppointmentTime, new { htmlAttributes = new { @class = "form-control timepicker" } })
@Html.ValidationMessageFor(model => model.AppointmentTime, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PatientName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PatientName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PatientName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PhoneNumber, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Book Appointment" class="btn btn-default" />
</div>
</div>
</div>
}
Payment Process Page
This view handles the payment process. After an appointment is booked, the patient is redirected to the payment page. Here, we demonstrate integration with Stripe for secure payment processing.
// Views/Payment/ProcessPayment.cshtml
@model YourProject.Models.AppointmentModel
@{
// In a real scenario, setup necessary parameters received from the controller.
}
<div class="payment-container">
<h4>Payment for Appointment</h4>
<hr />
<form asp-action="ProcessPayment" method="post">
@Html.AntiForgeryToken()
<input type="hidden" name="AppointmentId" value="@Model.Id" />
<div class="form-group">
<label>Amount ($)</label>
<input type="number" name="Amount" value="@Model.Fee" readonly class="form-control" />
</div>
<div class="form-group">
<input type="submit" value="Pay Now" class="btn btn-primary" />
</div>
</form>
</div>
Success Page with Download Receipt
After payment is processed, the user reaches a successful page that confirms the appointment and displays a downloadable receipt. The receipt is generated in PDF format.
// Views/Success/Index.cshtml
@model YourProject.Models.ReceiptModel
<div class="success-page">
<h4>Appointment Booked Successfully!</h4>
<hr />
<p>Appointment Date: @Model.AppointmentDate</p>
<p>Doctor Name: @Model.DoctorName</p>
<p>Patient Name: @Model.PatientName</p>
<p>Amount Paid: $@Model.AmountPaid</p>
<a href="@Url.Action("DownloadReceipt", "Success", new { id = Model.AppointmentDate.Ticks })" class="btn btn-success">
Download Receipt
</a>
</div>
Step 3: Creating the Controllers
Controllers are responsible for handling the application logic. The following sections detail essential controller actions for booking, payment processing, and receipt download functionality.
Home Controller for Appointment Booking
// Controllers/HomeController.cs
public class HomeController : Controller
{
// GET: Display booking form
public ActionResult BookAppointment()
{
// Populate list of doctors, e.g., from a database
ViewBag.Doctors = new SelectList(GetDoctors(), "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult BookAppointment(AppointmentModel appointment)
{
if(ModelState.IsValid)
{
// Save appointment into the database
// For example: db.Appointments.Add(appointment); db.SaveChanges();
// Set Fee for demonstration purposes
appointment.Fee = 100.00m;
// Redirect to the Payment Process view passing the appointment details
return RedirectToAction("Payment", "Payment", appointment);
}
return View(appointment);
}
// Simulated method to return doctor list
private IEnumerable<Doctor> GetDoctors()
{
return new List<Doctor> {
new Doctor { Id = 1, Name = "Dr. Smith" },
new Doctor { Id = 2, Name = "Dr. Johnson" }
};
}
}
Payment Controller for Processing Payments
// Controllers/PaymentController.cs
using Stripe;
public class PaymentController : Controller
{
public ActionResult Payment(AppointmentModel appointment)
{
return View(appointment);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ProcessPayment(PaymentModel payment)
{
// Example for Stripe integration: set your secret key
StripeConfiguration.ApiKey = "YOUR_STRIPE_SECRET_KEY";
var options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string> { "card" },
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
Currency = "usd",
ProductData = new SessionLineItemPriceDataProductDataOptions
{
Name = "Doctor Appointment"
},
UnitAmount = (long)(payment.Amount * 100) // converting dollars to cents
},
Quantity = 1,
},
},
Mode = "payment",
SuccessUrl = Url.Action("Index", "Success", null, Request.Url.Scheme),
CancelUrl = Url.Action("Payment", "Payment", null, Request.Url.Scheme)
};
var service = new SessionService();
Session session = service.Create(options);
// Redirect to Stripe Checkout
return Redirect(session.Url);
}
}
Success Controller for Receipt Generation
// Controllers/SuccessController.cs
using System.Text;
public class SuccessController : Controller
{
public ActionResult Index()
{
// Generate receipt data. In a real application, fetch details from the database.
ReceiptModel receipt = new ReceiptModel
{
AppointmentDate = DateTime.Now,
DoctorName = "Dr. Smith",
PatientName = "Jane Doe",
AmountPaid = 100.00m
};
return View(receipt);
}
public ActionResult DownloadReceipt(long id)
{
// Create a simple HTML receipt and convert to PDF in real scenario.
ReceiptModel receipt = new ReceiptModel
{
AppointmentDate = DateTime.Now,
DoctorName = "Dr. Smith",
PatientName = "Jane Doe",
AmountPaid = 100.00m
};
string receiptHtml = RenderRazorViewToString("Receipt", receipt);
byte[] pdfBytes = Encoding.UTF8.GetBytes(receiptHtml);
return File(pdfBytes, "application/pdf", "Receipt.pdf");
}
// Helper method to render view to string
private string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new System.IO.StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
Overview of Code Structure
The table below provides a concise overview of the key files and functions incorporated in the project.
| File/Section | Description |
|---|---|
| AppointmentModel.cs | Defines appointment details such as doctor, patient, date, time, and fee. |
| PaymentModel.cs | Tracks payment details and status for corresponding appointments. |
| ReceiptModel.cs | Contains information to be displayed on the receipt. |
| BookAppointment.cshtml | View for booking appointments with user input fields. |
| ProcessPayment.cshtml | View for processing the payment including integration with Stripe. |
| Index.cshtml (Success) | Success page immediately after payment, offering a download link for the receipt. |
| HomeController | Handles appointment booking logic and initial form display. |
| PaymentController | Manages payment processing and interfaces with the payment gateway API. |
| SuccessController | Generates the receipt and provides the functionality to download it as a PDF. |
Additional Considerations
When deploying this system, ensure you have implemented necessary error handling, input validation, and security best practices. Consider the following:
- Utilize HTTPS for secure data transfers.
- Protect against SQL injection and cross-site scripting using ASP.NET MVC built-in mechanisms.
- Store sensitive configuration values such as API keys securely (e.g., in environment variables or secure configuration files).
- Implement logging and exception handling for troubleshooting and maintenance.
- Test the system thoroughly including unit tests and integration tests, particularly for payment processing and PDF generation.
References
- ASP.NET MVC Documentation - Microsoft Learn
- Doctor Appointment Scheduling Tutorial - DayPilot
- Visual Doctor Appointment Scheduling - CodeProject
- Generate Receipt PDF in ASP.NET - ASPSnippets
-
Stripe API Documentation - Stripe
Recommended Further Queries
Last updated March 19, 2025