How to make crud operation in asp.net mvc aspx without database nor entity framework

Learn how to make crud operation in asp.net mvc aspx without database nor entity framework with practical examples, diagrams, and best practices. Covers asp.net, asp.net-mvc, entity-framework devel...

CRUD Operations in ASP.NET MVC (ASPX) Without Database or Entity Framework

Illustration of a web application performing CRUD operations on in-memory data, bypassing a database.

Learn how to implement basic Create, Read, Update, and Delete (CRUD) operations in an ASP.NET MVC application using ASPX views, without relying on a database or Entity Framework. This guide focuses on in-memory data management for demonstration purposes.

Developing web applications often involves managing data through CRUD operations. While databases and ORMs like Entity Framework are standard for persistence, there are scenarios where you might need to perform CRUD operations without them. This could be for rapid prototyping, testing, or working with temporary, in-memory data. This article will guide you through building a simple ASP.NET MVC 4 application using ASPX views to demonstrate these operations using a static list as a data store.

Understanding the Approach: In-Memory Data Store

Instead of connecting to a SQL Server database or using Entity Framework, we will simulate a data store using a static List<T> in our application. This list will hold our model objects, and all CRUD operations will directly manipulate this list. This approach is suitable for learning the MVC pattern and CRUD logic without the overhead of database setup, but it's crucial to understand that data will not persist across application restarts.

flowchart TD
    A[User Request] --> B{Controller Action}
    B --> C{Manipulate Static List}
    C --> D{Return View with Data}
    D --> A

Flow of in-memory CRUD operations in ASP.NET MVC.

Setting Up the Project and Model

First, create a new ASP.NET MVC 4 Web Application project in Visual Studio, choosing the 'Empty' template and selecting 'ASPX' as the view engine. Next, we'll define a simple model class and a static data store to hold our items.

namespace MvcInMemoryCrud.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    public static class ProductRepository
    {
        private static List<Product> _products;
        private static int _nextId = 1;

        static ProductRepository()
        {
            _products = new List<Product>
            {
                new Product { Id = _nextId++, Name = "Laptop", Price = 1200.00m },
                new Product { Id = _nextId++, Name = "Mouse", Price = 25.50m },
                new Product { Id = _nextId++, Name = "Keyboard", Price = 75.00m }
            };
        }

        public static IEnumerable<Product> GetAll()
        {
            return _products;
        }

        public static Product GetById(int id)
        {
            return _products.FirstOrDefault(p => p.Id == id);
        }

        public static void Add(Product product)
        {
            product.Id = _nextId++;
            _products.Add(product);
        }

        public static void Update(Product product)
        {
            var existingProduct = _products.FirstOrDefault(p => p.Id == product.Id);
            if (existingProduct != null)
            {
                existingProduct.Name = product.Name;
                existingProduct.Price = product.Price;
            }
        }

        public static void Delete(int id)
        {
            _products.RemoveAll(p => p.Id == id);
        }
    }
}

Product Model and Static Repository (ProductRepository.cs)

Implementing the Controller Actions

Now, we'll create a controller (ProductController.cs) that will handle the HTTP requests and interact with our ProductRepository. Each CRUD operation will have corresponding actions.

using System.Web.Mvc;
using MvcInMemoryCrud.Models;

namespace MvcInMemoryCrud.Controllers
{
    public class ProductController : Controller
    {
        // GET: Product
        public ActionResult Index()
        {
            var products = ProductRepository.GetAll();
            return View(products);
        }

        // GET: Product/Details/5
        public ActionResult Details(int id)
        {
            var product = ProductRepository.GetById(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        // GET: Product/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Product/Create
        [HttpPost]
        public ActionResult Create(Product product)
        {
            if (ModelState.IsValid)
            {
                ProductRepository.Add(product);
                return RedirectToAction("Index");
            }
            return View(product);
        }

        // GET: Product/Edit/5
        public ActionResult Edit(int id)
        {
            var product = ProductRepository.GetById(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        // POST: Product/Edit/5
        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                ProductRepository.Update(product);
                return RedirectToAction("Index");
            }
            return View(product);
        }

        // GET: Product/Delete/5
        public ActionResult Delete(int id)
        {
            var product = ProductRepository.GetById(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        // POST: Product/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            ProductRepository.Delete(id);
            return RedirectToAction("Index");
        }
    }
}

ProductController.cs with CRUD actions

Creating the ASPX Views

Finally, we need to create the corresponding ASPX views for each controller action. These views will display the data and provide forms for creating and editing products. Remember to right-click on each action method in the controller and select 'Add View...' to generate the basic view structure, then customize it as shown below.

Index.aspx (List Products)

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcInMemoryCrud.Models.Product>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Products </asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Products</h2>

<p>
    <%= Html.ActionLink("Create New", "Create") %>
</p>
<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
        <th>
            Price
        </th>
        <th></th>
    </tr>

<% foreach (var item in Model) {
    %><tr>
        <td>
            <%= Html.DisplayFor(modelItem => item.Id) %>
        </td>
        <td>
            <%= Html.DisplayFor(modelItem => item.Name) %>
        </td>
        <td>
            <%= Html.DisplayFor(modelItem => item.Price) %>
        </td>
        <td>
            <%= Html.ActionLink("Edit", "Edit", new { id=item.Id }) %> |
            <%= Html.ActionLink("Details", "Details", new { id=item.Id }) %> |
            <%= Html.ActionLink("Delete", "Delete", new { id=item.Id }) %>
        </td>
    </tr>
<% } %>

</table>

</asp:Content>

Create.aspx (Add New Product)

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcInMemoryCrud.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Create</h2>

<%= Html.ValidationSummary(true) %>

<% using (Html.BeginForm()) { %>

    <fieldset>
        <legend>Product</legend>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Name) %>
        </div>
        <div class="editor-field">
            <%= Html.EditorFor(model => model.Name) %>
            <%= Html.ValidationMessageFor(model => model.Name) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Price) %>
        </div>
        <div class="editor-field">
            <%= Html.EditorFor(model => model.Price) %>
            <%= Html.ValidationMessageFor(model => model.Price) %>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

<% } %>

<div>
    <%= Html.ActionLink("Back to List", "Index") %>
</div>

</asp:Content>

Edit.aspx (Update Product)

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcInMemoryCrud.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Edit </asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Edit</h2>

<%= Html.ValidationSummary(true) %>

<% using (Html.BeginForm()) { %>

    <fieldset>
        <legend>Product</legend>

        <%= Html.HiddenFor(model => model.Id) %>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Name) %>
        </div>
        <div class="editor-field">
            <%= Html.EditorFor(model => model.Name) %>
            <%= Html.ValidationMessageFor(model => model.Name) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(model => model.Price) %>
        </div>
        <div class="editor-field">
            <%= Html.EditorFor(model => model.Price) %>
            <%= Html.ValidationMessageFor(model => model.Price) %>
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

<% } %>

<div>
    <%= Html.ActionLink("Back to List", "Index") %>
</div>

</asp:Content>

Details.aspx (View Product)

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcInMemoryCrud.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Details </asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Details</h2>

<fieldset>
    <legend>Product</legend>

    <div class="display-label">
         <%= Html.DisplayNameFor(model => model.Id) %>
    </div>
    <div class="display-field">
        <%= Html.DisplayFor(model => model.Id) %>
    </div>

    <div class="display-label">
         <%= Html.DisplayNameFor(model => model.Name) %>
    </div>
    <div class="display-field">
        <%= Html.DisplayFor(model => model.Name) %>
    </div>

    <div class="display-label">
         <%= Html.DisplayNameFor(model => model.Price) %>
    </div>
    <div class="display-field">
        <%= Html.DisplayFor(model => model.Price) %>
    </div>
</fieldset>
<p>
    <%= Html.ActionLink("Edit", "Edit", new { id=Model.Id }) %> |
    <%= Html.ActionLink("Back to List", "Index") %>
</p>

</asp:Content>

Delete.aspx (Confirm Delete)

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcInMemoryCrud.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Delete </asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>Product</legend>

    <div class="display-label">
         <%= Html.DisplayNameFor(model => model.Id) %>
    </div>
    <div class="display-field">
        <%= Html.DisplayFor(model => model.Id) %>
    </div>

    <div class="display-label">
         <%= Html.DisplayNameFor(model => model.Name) %>
    </div>
    <div class="display-field">
        <%= Html.DisplayFor(model => model.Name) %>
    </div>

    <div class="display-label">
         <%= Html.DisplayNameFor(model => model.Price) %>
    </div>
    <div class="display-field">
        <%= Html.DisplayFor(model => model.Price) %>
    </div>
</fieldset>
<% using (Html.BeginForm()) { %>
    <p>
        <input type="submit" value="Delete" /> |
        <%= Html.ActionLink("Back to List", "Index") %>
    </p>
<% } %>

</asp:Content>

Running the Application

After setting up the model, controller, and views, you can run the application. Navigate to /Product in your browser, and you should see the list of products. You can then use the 'Create New', 'Edit', 'Details', and 'Delete' links to perform the respective CRUD operations on the in-memory data.

1. Step 1: Build the Project

Press Ctrl+Shift+B or go to Build > Build Solution in Visual Studio to compile your project.

2. Step 2: Run the Application

Press F5 or click the 'Run' button in Visual Studio. This will launch the application in your default browser.

3. Step 3: Navigate to Products

If your default route isn't set to ProductController, manually navigate to http://localhost:[your_port]/Product in your browser to see the list of products and interact with the CRUD functionality.

This comprehensive guide demonstrates how to implement basic CRUD operations in an ASP.NET MVC 4 application using ASPX views and an in-memory data store. While this approach is excellent for understanding the core MVC pattern and CRUD logic, remember that for persistent data storage in real-world applications, you would integrate a database and an ORM like Entity Framework.