Sunday, November 25, 2018

MVC Web API Sample

Referred Link with some changes.

https://www.c-sharpcorner.com/article/crud-Asp-Net-web-api-with-entity-framework-in-Asp-Net-mvc/

1. Create new Project and select Web API Project.
2. Create the EF ADO.NET Entity model
3. Build the project
4. Create Web API controllers for all tables.
5. Check if all APIs are working fine like below:
http://localhost:62279/api/Categories
http://localhost:62279/api/ListItems
6. Now add a new MVC project with name ending with Presentation to the solution.
7. Add Models for all the tables just copy from edmx file or use following template.
using System;
using System.ComponentModel.DataAnnotations;

namespace MVCPersatantion.Models
{
public class Customer
{
[Display(Name = "CustomerId")]
public int CustomerId { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
[Display(Name = "Address")]
public string Address { get; set; }
[Display(Name = "MobileNo")]
public string MobileNo { get; set; }
[Display(Name = "Birthdate")]
[DataType(DataType.Date)]
public DateTime Birthdate { get; set; }
[Display(Name = "EmailId")]
public string EmailId { get; set; }

}

}
8. Create ViewModel folder and add ViewModel files.
9. Add all ViewModel files like CategoryViewModel
10. Add the following code, add the missing dll if it is as follows.

Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

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

namespace MVCOutOfBasketClient.Models
{
    public class CategoryClient
    {
        private string Base_URL = "http://localhost:62279/api/";

        public IEnumerable findAll()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.GetAsync("Categories").Result;

                if (response.IsSuccessStatusCode)
                    return response.Content.ReadAsAsync>().Result;
                return null;
            }
            catch
            {
                return null;
            }
        }
        public Category 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("Categories/" + id).Result;

                if (response.IsSuccessStatusCode)
                    return response.Content.ReadAsAsync().Result;
                return null;
            }
            catch
            {
                return null;
            }
        }
        public bool Create(Category Category)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.PostAsJsonAsync("Categories", Category).Result;
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
        public bool Edit(Category Category)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Base_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = client.PutAsJsonAsync("Categories/" + Category.CustomerId, Category).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("Categories/" + id).Result;
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }
    }
}


11. Add MVC Controllers

We have to add a controller, so for this right click on Controllers folder and add a controller and give the name for ex.Customer and write the code and call the service client method.



using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MVCOutOfBasketClient.Models;

namespace MVCOutOfBasketClient.Controllers
{
    public class QuantityUnitsController : Controller
    {
        // GET: QuantityUnits
        public ActionResult Index()
        {
            QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
            List listQuantityUnit = new List();
            listQuantityUnit = (List) quantityUnitClient.findAll();
         
            return View(listQuantityUnit);
        }

        // GET: QuantityUnits/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
            QuantityUnit quantityUnit = new QuantityUnit();
            quantityUnit = (QuantityUnit)quantityUnitClient.find((int)id);

            if (quantityUnit == null)
            {
                return HttpNotFound();
            }
            return View(quantityUnit);
        }

        // GET: QuantityUnits/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: QuantityUnits/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "QuantityUnitId,QuantityUnitName,QuantityUnitDescription")] QuantityUnit quantityUnit)
        {
            if (ModelState.IsValid)
            {
                QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
                quantityUnitClient.Create(quantityUnit);
                return RedirectToAction("Index");
            }

            return View(quantityUnit);
        }

        // GET: QuantityUnits/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
            QuantityUnit quantityUnit = quantityUnitClient.find((int)id);

            if (quantityUnit == null)
            {
                return HttpNotFound();
            }
            return View(quantityUnit);
        }

        // POST: QuantityUnits/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "QuantityUnitId,QuantityUnitName,QuantityUnitDescription")] QuantityUnit quantityUnit)
        {
            if (ModelState.IsValid)
            {
                QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
                quantityUnitClient.Edit(quantityUnit);             

                return RedirectToAction("Index");
            }
            return View(quantityUnit);
        }

        // GET: QuantityUnits/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
            QuantityUnit quantityUnit = quantityUnitClient.find((int)id);

            if (quantityUnit == null)
            {
                return HttpNotFound();
            }
            return View(quantityUnit);
        }

        // POST: QuantityUnits/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            QuantityUnitClient quantityUnitClient = new QuantityUnitClient();
            QuantityUnit quantityUnit = null;
            quantityUnit = quantityUnitClient.find((int)id);
            if (quantityUnit != null)
            {
                quantityUnitClient.Delete((int)id);
            }
            else
            {
                return HttpNotFound();
            }
            return RedirectToAction("Index");
        }
    }
}

No comments: