CRUD Operations In An ASP.NET MVC Web Application Using Entity Framework

Here's an example of how to perform CRUD operations in an ASP.NET MVC web application using Entity Framework,

Step 1

Create a new controller for your Entity Framework model, as described in the previous answer.

Step 2

In the controller, add action methods for each CRUD operation you want to perform. For example:

public ActionResult Index()
{
    var data = db.MyTable.ToList();
    return View(data);
}

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(MyTable item)
{
    if (ModelState.IsValid)
    {
        db.MyTable.Add(item);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(item);
}

public ActionResult Edit(int id)
{
    var item = db.MyTable.Find(id);
    if (item == null)
    {
        return HttpNotFound();
    }
    return View(item);
}

[HttpPost]
public ActionResult Edit(MyTable item)
{
    if (ModelState.IsValid)
    {
        db.Entry(item).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(item);
}

public ActionResult Delete(int id)
{
    var item = db.MyTable.Find(id);
    if (item == null)
    {
        return HttpNotFound();
    }
    return View(item);
}

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    var item = db.MyTable.Find(id);
    db.MyTable.Remove(item);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Step 3

For each action method that returns a view, create a corresponding view file with the same name as the method. For example, the Create() method would have a view file called Create.cshtml.

Step 4

In the views, use Razor syntax to create forms and display data. For example, the Create.cshtml view might look like this,

@model MyProject.Models.MyTable

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        @Html.LabelFor(model => model.Name)
        @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Description)
        @Html.TextBoxFor(model => model.Description, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Description)
    </div>

    <button type="submit" class="btn btn-primary">Save</button>
}

Step 5

Finally, set up routing in your application so that the correct controller and action methods handle requests to the appropriate URLs. For example:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

With this setup, you can create, read, update, and delete records from your Entity Framework model using the ASP.NET MVC framework.


Similar Articles