Skip to content

Instantly share code, notes, and snippets.

@clickCA
Last active July 24, 2023 07:00
Show Gist options
  • Select an option

  • Save clickCA/533a2691ba6ea89c5360ad0506665e11 to your computer and use it in GitHub Desktop.

Select an option

Save clickCA/533a2691ba6ea89c5360ad0506665e11 to your computer and use it in GitHub Desktop.

Model Example

// Task.cs (Model)
public class Task
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

View Example

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="YourNamespace.Index" %>

<!DOCTYPE html>
<html>
<head>
    <title>Task List</title>
</head>
<body>
    <h2>Task List</h2>

    <ul>
        <% foreach (var task in Model) { %>
            <li>
                <strong><%= task.Title %></strong>
                <p><%= task.Description %></p>
            </li>
        <% } %>
    </ul>

    <h2>Add New Task</h2>

    <form runat="server" action="Task/Add" method="post">
        <label>Title:</label>
        <input type="text" name="Title" required />
        <br />
        <label>Description:</label>
        <textarea name="Description"></textarea>
        <br />
        <input type="submit" value="Add Task" />
    </form>
</body>
</html>

Controller Example

// TaskController.cs (Controller)
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

public class TaskController : Controller
{
    private static List<Task> tasks = new List<Task>();

    public IActionResult Index()
    {
        // Pass the list of tasks to the View
        return View(tasks);
    }

    [HttpPost]
    public IActionResult Add(Task task)
    {
        // Simple validation for the task title
        if (ModelState.IsValid && !string.IsNullOrEmpty(task.Title))
        {
            task.Id = tasks.Count + 1;
            tasks.Add(task);
            return RedirectToAction("Index");
        }

        // If validation fails, return to the same View to show error messages
        return View("Index", tasks);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment