Sunday 19 July 2020

CRUD with Asp.Net MVC & WebApi using EF & Validations

In this article we will learn crud operation in Asp.Net MVC & WebApi

Step 1: Create DB and add table EmployeeDetails as below.

Step 2: Choose Asp.Net Web Application in visual studio.Create Solution in which we have to add two projects webapi and mvc as shown below

Step 3: Now we have to add a class so right click on model floder in webapi project & use ADO Net Entity Data Model 

Step 4: Now we have to add WebApi Controller, so right click on controllers folder. Select webapi2 controller with actions using Entity framework.

Note: This will automatically generates following code
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebApiMVC.Models;

namespace WebApiMVC.Controllers
{
    public class EmployeeDetailsController : ApiController
    {
        private EmpDbEntities db = new EmpDbEntities();

        // GET: api/EmployeeDetails
        public IQueryable<EmployeeDetail> GetEmployeeDetails()
        {
            return db.EmployeeDetails;
        }

        // GET: api/EmployeeDetails/5
        [ResponseType(typeof(EmployeeDetail))]
        public IHttpActionResult GetEmployeeDetail(int id)
        {
            EmployeeDetail employeeDetail = db.EmployeeDetails.Find(id);
            if (employeeDetail == null)
            {
                return NotFound();
            }

            return Ok(employeeDetail);
        }

        // PUT: api/EmployeeDetails/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutEmployeeDetail(int id, EmployeeDetail employeeDetail)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != employeeDetail.EmpId)
            {
                return BadRequest();
            }

            db.Entry(employeeDetail).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeDetailExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/EmployeeDetails
        [ResponseType(typeof(EmployeeDetail))]
        public IHttpActionResult PostEmployeeDetail(EmployeeDetail employeeDetail)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.EmployeeDetails.Add(employeeDetail);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = employeeDetail.EmpId }, employeeDetail);
        }

        // DELETE: api/EmployeeDetails/5
        [ResponseType(typeof(EmployeeDetail))]
        public IHttpActionResult DeleteEmployeeDetail(int id)
        {
            EmployeeDetail employeeDetail = db.EmployeeDetails.Find(id);
            if (employeeDetail == null)
            {
                return NotFound();
            }

            db.EmployeeDetails.Remove(employeeDetail);
            db.SaveChanges();

            return Ok(employeeDetail);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool EmployeeDetailExists(int id)
        {
            return db.EmployeeDetails.Count(e => e.EmpId == id) > 0;
        }
    }



Copy the webapi url "http://localhost:63394/api" we have to use in MVC project.

Step 5: Now we have to add an MVC project for consuming the web api service.So first we have to add a model class. so here we took Employee class. Fo this right click of models folder and add class give name as Employee.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using rm = System.Web.Mvc;

namespace MVCProject.Models
{
    public class Employee
    {
        [Key]
        [Display(Name = "EmployeeId")]
        public int EmpId { get; set; }
        [Display(Name = "EmployeeName")]
        [Required(ErrorMessage = "Employee Name is required")]
        [StringLength(15,MinimumLength =4, ErrorMessage = "Name must be between 4 to 15 characters" )]
        public string EmpName { get; set; }
        [Display(Name = "BirthDate")]
        public string DateofBirth { get; set; }
        [Display(Name = "EmailId")]
        [Required(ErrorMessage = "EmailId is required")]
        public string EmailId { get; set; }
        [Display(Name = "Gender")]
        [Required(ErrorMessage = "Gender is required")]
        public string Gender { get; set; }
        [Display(Name = "Address")]
        public string Address { get; set; }
        [Display(Name = "PinCode")]
        public string PinCode { get; set; }
    }
Now we have to add the ViewModel folder and a class for EmployeeViewModel.cs 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCProject.Models
{
    public class EmployeeViewModel
    {
        public Employee employee { get; set; }
    }

Step 6: We have to add a class for consuming the webapi service so add class EmployeeClient.cs and write the below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;

namespace MVCProject.Models
{
    public class EmployeeClient
    {
        private string Base_URL = "http://localhost:63394/api/";

        public IEnumerable<Employee> FindAll()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("EmployeeDetails").Result;

                if (response.IsSuccessStatusCode)
                    return response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;
                return null;
            }
            catch
            {
                return null;
            }
        }
        public Employee find(int id)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("EmployeeDetails/" + id).Result;

                if (response.IsSuccessStatusCode)
                    return response.Content.ReadAsAsync<Employee>().Result;
                return null;
            }
            catch
            {
                return null;
            }
        }
        public bool Create(Employee employee)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.PostAsJsonAsync("EmployeeDetails", employee).Result;
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
        public bool Edit(Employee employee)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.PutAsJsonAsync("EmployeeDetails/" + employee.EmpId, employee).Result;
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
        public bool Delete(int id)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.DeleteAsync("EmployeeDetails/" + id).Result;
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
    }
Step 7: We have to add controller , right click on controller folder & add controller with name as Employee write below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCProject.Models;

namespace MVCProject.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            EmployeeClient ec = new EmployeeClient();
            ViewBag.listEmployee = ec.FindAll();
            return View();
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View("Create");
        }
        [HttpPost]
        public ActionResult Create(EmployeeViewModel evm)
        {
            EmployeeClient ec = new EmployeeClient();
            ec.Create(evm.employee);
            return RedirectToAction("Index");
        }
        public ActionResult Delete(int id)
        {
            EmployeeClient ec = new EmployeeClient();
            ec.Delete(id);
            return RedirectToAction("Index");
        }
        [HttpGet]
        public ActionResult Edit(int id)
        {
            EmployeeClient ec = new EmployeeClient();
            EmployeeViewModel evm = new EmployeeViewModel();
            evm.employee = ec.find(id);
            return View("Edit", evm);
        }
        [HttpPost]
        public ActionResult Edit(EmployeeViewModel evm)
        {
            EmployeeClient ec = new EmployeeClient();
            ec.Edit(evm.employee);
            return RedirectToAction("Index");
        }     
 }
}
Step8: Now we have to create view page so first create Index page

Index.cshtml
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div align="center">
    <a href="@Url.Action("Create","Employee")" class="btn" style="color:green"> Add New Employee</a>
    <br /><br />
   
    <table cellpadding="2" class="table" cellspacing="2" border="1">
        <thead>
            <tr class="btn-primary">
                <th>EmployeeId</th>
                <th>EmployeeName</th>
                <th>DateOfBirth</th>
                <th>EmailId</th>
                <th>Gender</th>
                <th>Address</th>
                <th>PinCode</th>
                <th align="center">Actions</th>
            </tr>
        </thead>
        <tbody id="searchDetails">
            @foreach (var emp in ViewBag.listEmployee)
            {
                <tr class="btn-success">
                    <td>
                        @emp.EmpId
                    </td>
                    <td>
                        @emp.EmpName
                    </td>
                    <td>
                        @emp.DateofBirth
                    </td>
                    <td>
                        @emp.EmailId
                    </td>
                    <td>
                        @emp.Gender
                    </td>
                    <td>
                        @emp.Address
                    </td>
                    <td>
                        @emp.PinCode
                    </td>
                    <td>
                        <a onclick="return confirm('Do you want to Delete?')" href="@Url.Action("Delete","Employee",new
                                                                             {
                                                                                 id
                                                                              = emp.EmpId
                                                                             })">Delete</a>
                        ||
                        <a href="@Url.Action("Edit","Employee",new
                                                                             {
                                                                                 id
                                                                              = emp.EmpId
                                                                             })">Edit</a>
                    </td>

                </tr>
            }
        </tbody>
    </table>
</div>

Create.cshtml:

@model MVCProject.Models.EmployeeViewModel
@{
    ViewBag.Title = "Create";
}
    <script src="~/Scripts/jquery-3.3.1.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<h2>Create</h2>

<div align="center">
    @using (Html.BeginForm("Create", "Employee", FormMethod.Post))
    {
    <table class="table table-hover" >
        <tr>
            <td>
                @Html.LabelFor(model => model.employee.EmpName);
            </td>
            <td>
                @Html.TextBoxFor(model => model.employee.EmpName);
                @Html.ValidationMessageFor(model => model.employee.EmpName,"",new { @class="text-danger"})
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.employee.DateofBirth);
            </td>
            <td>
                @Html.TextBoxFor(model => model.employee.DateofBirth);
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.employee.EmailId);
            </td>
            <td>
                @Html.TextBoxFor(model => model.employee.EmailId);
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.employee.Gender);
            </td>
            <td>
                @Html.TextBoxFor(model => model.employee.Gender);
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.employee.Address);
            </td>
            <td>
                @Html.TextBoxFor(model => model.employee.Address);
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(model => model.employee.PinCode);
            </td>
            <td>
                @Html.TextBoxFor(model => model.employee.PinCode);
            </td>
        </tr>
        <tr>
            <td>
               
            </td>
            <td>
                <input type="submit" value="Save" />
            </td>
        </tr>
    </table>
    }

</div> 

Edit.cshtml:

@model MVCProject.Models.EmployeeViewModel
@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

<div align="center" width="500px">
    @using (Html.BeginForm("Edit", "Employee", FormMethod.Post))
    {
        <table class="table" width="400px" cellpadding="20">
            <tr class="btn-default">
                <td>
                    @Html.LabelFor(model => model.employee.EmpName)
                </td>

                <td>
                    @Html.TextBoxFor(model => model.employee.EmpName)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.employee.DateofBirth)
                </td>

                <td>
                    @Html.TextBoxFor(model => model.employee.DateofBirth)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.employee.EmailId)
                </td>

                <td>
                    @Html.TextBoxFor(model => model.employee.EmailId)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.employee.Address)
                </td>

                <td>
                    @Html.TextBoxFor(model => model.employee.Address)
                </td>
            </tr>
            <tr>
                <td>
                    @Html.LabelFor(model => model.employee.PinCode)
                </td>

                <td>
                    @Html.TextBoxFor(model => model.employee.PinCode)
                </td>
            </tr>
            <tr>
                <td></td>

                <td>
                    <input type="submit" value="Save" /> &nbsp;<a class="btn-primary" href="@Url.Action("Index","Employee")"> Back</a>
                    @Html.HiddenFor(model => model.employee.EmpId)
                </td>
            </tr>
        </table>
    }
</div>

Finally we have completed so now we execute the application but one thing here is important that we have to run both webapi & mvc projects simultaneously so make this possible,right click on solution & go to properties & then startup project option and select multiple startup projects.
Then run the projects and see the result as below 

See the List of Employee



See the Create page


See the validation error message


See the Edit Page


Note: In EmployeeClient.cs class some code is continuously repeated . so to avoid this repetition, we can add  new static class to write that code & then call that class .


PostedBy:pankaj_bhakre

No comments:

Post a Comment