MVC CRUD Operation With Web API

16:24

Introduction

In this post I want to show how to implement CRUD operation in MVC with web API. To know more about Web API, Please follow my previous article.

CRUD Image



Step To Create Application

Follow the following step to create Api controller:

Table

    CREATE TABLE [dbo].[Person] (
    [ID]      INT            IDENTITY (1, 1) NOT NULL,
    [Name]    NVARCHAR (50)  NOT NULL,
    [Address] NVARCHAR (500) NOT NULL,
    [DOB]     DATE           NOT NULL,
    PRIMARY KEY CLUSTERED ([ID] ASC)
)

Entity Data Model



Views

Index:
@model IEnumerable<MVC_CRUD_Operation_With_WebAPI.Models.Person>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<style>
    table { border:2px solid #0094ff; width:80%; }
    table th {border-left:1px solid #0094ff; text-align:center; line-height:50px;background-color:#0094ff;color:#fff;}
    table tr { border-top:1px solid #0094ff; }
    table tr td { border-left:1px solid #0094ff; padding:10px; }
    table tr td a {color:#6476c8 !important; }
    table tr td a:hover {color:#0613f7 !important; background-color:none !important; }
</style>


<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.DOB)
        </th>
        <th>Action</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Address)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DOB)
        </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> 
Create:
@model MVC_CRUD_Operation_With_WebAPI.Models.Person

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

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

    <fieldset>
        <legend>Person</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.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>

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

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

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Details:
@model MVC_CRUD_Operation_With_WebAPI.Models.Person

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Person</legend>

    <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.Address)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Address)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.DOB)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.DOB)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>
Edit:
@model MVC_CRUD_Operation_With_WebAPI.Models.Person

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

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

    <fieldset>
        <legend>Person</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.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>

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

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

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Delete:
@model MVC_CRUD_Operation_With_WebAPI.Models.Person

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

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

    <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.Address)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Address)
    </div>

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

Controller

using MVC_CRUD_Operation_With_WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_CRUD_Operation_With_WebAPI.Controllers
{
    public class TestController : Controller
    {
        #region "DECLARATION"
        APIController db = new APIController();
        #endregion


        #region "GET"
        public ActionResult Index()
        {
            var list = db.Get();
            return View(list);
        }

        public ActionResult Details(int id)
        {
            Person person = db.Get(id);
            return View(person);
        }
        #endregion

        #region "POST"
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Person obj)
        {
            try
            {
                db.Post(obj);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region "PUT"
        public ActionResult Edit(int id)
        {
            Person person = db.Get(id);
            return View(person);
        }

        [HttpPost]
        public ActionResult Edit(int id, Person obj)
        {
            try
            {
                db.Put(id, obj);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion

        #region "DELETE"
        public ActionResult Delete(int id)
        {
            Person person = db.Get(id);
            return View(person);
        }

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                db.Delete(id);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        #endregion
    }
}

API Controller

    using MVC_CRUD_Operation_With_WebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MVC_CRUD_Operation_With_WebAPI.Controllers
{
    public class APIController : ApiController
    {
        #region "API DECLARATION"
        dbEntities db = new dbEntities();
        #endregion

        #region "API GET"
        public IEnumerable Get()
        {
            return db.Person.ToList();
        }

        public Person Get(int id)
        {
            return db.Person.Find(id);
        }
        #endregion

        #region "API POST"
        public void Post(Person val)
        {
            try
            {
                Person obj = new Person();
                obj.Name = val.Name;
                obj.Address = val.Address;
                obj.DOB = Convert.ToDateTime(val.DOB);
                db.Person.Add(obj);
                db.SaveChanges();
            }
            catch (Exception) { }
        }
        #endregion

        #region "API PUT"
        public void Put(int id, Person obj)
        {
            try
            {
                db.Entry(obj).State = System.Data.EntityState.Modified;
                db.SaveChanges();
            }
            catch (Exception) { }
        }
        #endregion

        #region "API DELETE"
        public void Delete(int id)
        {
            Person obj = db.Person.Find(id);
            db.Person.Remove(obj);
            db.SaveChanges();
        }
        #endregion
    }
}

Download

You can download this application zip file here

Conclusion

I create this MVC application CRUD operation with Web API. If you need another help. Please send me a comment.

You Might Also Like

0 comments