create crud web app in csharp

Creating a CRUD (Create, Read, Update, Delete) web application in C# involves the following steps:

  1. Start by creating a new ASP.NET web application project
  2. Add a new entity model to your project using Entity Framework
  3. Create a controller that will handle the CRUD operations
  4. Create views for each action in the CRUD operations
  5. Set up routing for your controller

Here's a general example of creating a CRUD web app in C# using Entity Framework.

First, add the Entity Framework package to your project. You can do this by opening the NuGet Package Manager Console and running the command:

main.cs
Install-Package EntityFramework
32 chars
2 lines

Next, create a new Movie entity model with properties for the movie's title, release date, and genre.

main.cs
public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
}
177 chars
8 lines

Then, create a new MoviesController with actions for Create, Read, Update, and Delete. The following code shows an example of the Create action:

main.cs
[HttpPost]
public ActionResult Create(Movie movie)
{
    // Add the new movie to the database
    db.Movies.Add(movie);
    db.SaveChanges();
    
    return RedirectToAction("Index");
}
187 chars
10 lines

Next, create views for each action using Razor syntax. Here's an example code snippet from the Index view that displays a list of movies:

main.cs
@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.Title)</td>
        <td>@Html.DisplayFor(modelItem => item.ReleaseDate)</td>
        <td>@Html.DisplayFor(modelItem => item.Genre)</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>
}
471 chars
13 lines

Finally, set up routing for your controller using attributes or by configuring it in the App_Start/RouteConfig.cs file.

main.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
311 chars
12 lines

gistlibby LogSnag