Thursday 7 January 2016

web api with entity framework example in MVC

You can give the answer of below question after complete this exercise.


  • Webapi example in mvc 5 
  • How to add Web API to an existing ASP.NET MVC (5) 
  • Differnce in WEBApi Controller and MVC Controller
  • List of Verb in WebAPI
  • How to place Routing for WebAPI
  • How to check the WEBApi Get
  • How to use Advance Rest Client.
  • How to  Check WEBApi Post
  • How to  Check WEBApi Put
  • How to  Check WEBApi Delete
  • Convert object to json in MVC.
  • How to Use WebClient to call WebApi
  • How to call WebApi through Webpage
  • call web api from mvc controller
  • How to declare local variable in MVc in Loop
  • How to use @Html.BegainForm
  • How to create Partial view.
  • How to call partial View in MVC
  • How to call web api post Action WebClient
  • How to call web api Put action WebClient
  • How to call web api Delete in WebClient.
  • How to delete record in web api using WebClient
  • Edit operation in mvc 4 with model pop




Demonstrating a simple application using MVC, WebApi and EntityFramework;
Web api example in mvc 5


·         Entity Framework samples for Insert, Update and delete
·         Web Api samples for Insert, Update and delete.
·         MVC Samples Insert, Update and Delete


Entity Framework Samples for Insert, Update and Delete

So let’s first create a table, I am demonstrating for maintain the country table. Where we have two columns countryId and CountryName like below;

1. A.  Create Table


1. B.  Associate that table with your entity frame work.
You can follow below article (Steps)  to create Entity frame work
Entity framework in asp.net  :  


Now you will get the table like below if you will see the designer;

Web API Sample for Samples for Insert, Update and Delete

Below code will cover the below topics

  1. Webapi example in mvc 5 
  2. How to add Web API to an existing ASP.NET MVC (5) 



1.       A. Add a new class for WebApi ; Following below steps to create it.
2.       Click on controller à Add à Controller as in screen.
(Step to create New WEBApi



Once you click on controller you will get the below window with different options.
I have selected the WEB API 2 Controller with read/write action as I want the code skeleton for All the operation of WEB API
You can select the WEB API 2 Controller – Empty also but there it will generate the empty class.


Now Click on Add than it will ask for controller name, provide the name of controller than Ok.
It will generate the code for you like below as;
namespace SampleLibraryApplication.Controllers
{
    public class CountryController : ApiController
    {
        // GET api/my
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/my/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/my
        public void Post([FromBody]string value)
        {
        }

        // PUT api/my/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/my/5
        public void Delete(int id)
        {
        }
    }
}


  • List of Verb in WebAPI
There you can see there is different operation for WEBAPi based on verbs has created like GET, POST, PUT, DELETE and based on need it we will call that methods.
GET : Get the records.
POST : Add  New records.
PUT : Update Existing Records
DELETE : Delete existing records.

There is one difference with the normal controller and WEBApi controller is, it is inherited from ApiController.

3.       Place WEBApi code for Insert, Update and Delete (WEBapi Crud Operation) code to perform operations;
I am using entity framework to perform the CRUD operation as below;

public class CountryDetailsController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<Country> Get()
        {
            /// Get the list of all country
            LibraryApplicationEntities objCountry = new LibraryApplicationEntities();
            var v  = from o in objCountry.tblCountries
                    select new Country
                    {
                        CountryId = o.CountryId,
                        CountryName = o.CountryName
                    };

           return v;
        }

        // GET api/<controller>/5
        public Country Get(int id)
        {
            /// Get particular country
            LibraryApplicationEntities objCountry = new LibraryApplicationEntities();
            var v = (from o in objCountry.tblCountries
                     where o.CountryId == id
                     select new Country
                     {
                         CountryId = o.CountryId,
                         CountryName = o.CountryName
                     }).ToList().FirstOrDefault();
          
            return v;
        }

        // POST api/<controller>
         public void Post([FromBody]Country value)
        {
             /// Saving New country details
            LibraryApplicationEntities objCountry = new LibraryApplicationEntities();
            tblCountry newCountry = new tblCountry(){CountryName = value.CountryName};

            objCountry.tblCountries.Add(newCountry);
            objCountry.SaveChanges();
        }

        // PUT api/<controller>/5
         public void Put(int id, [FromBody]Country value)
        {
             /// Updating existing country
            using (var db = new LibraryApplicationEntities())
            {
                var result = db.tblCountries.SingleOrDefault(b => b.CountryId == id);
                if (result != null)
                {
                    result.CountryName = value.CountryName;
                    db.SaveChanges();
                }
            }
        }

        // DELETE api/<controller>/5
        public void Delete(int Id)
        {
            /// Delete Existing country
            LibraryApplicationEntities ctx = new LibraryApplicationEntities();
            var country = new tblCountry { CountryId = Id };
            ctx.tblCountries.Attach(country);
            ctx.tblCountries.Remove(country);
            ctx.SaveChanges();
        }
    }

4.       Placed the new routing rule for your WEbAPI into routeconfig.cs like below:

  • How to place Routing for WebAPI
routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );

5.       Now you can check your API using in browser, its working or not e.g; http://localhost:64622/api/countrydetails/ (Note : Application should be in running stage)
If everything is fine you will get result like;

How to check the WEBApi Get



6.       For POST and Delete you can see, Just install extension of Google chrome as Advance Rest client and there you can check like below. E.g. for post.

  • How to use Advance Rest Client.
  • How to  Check WEBApi Post
  • How to  Check WEBApi Delete



You can debug your code also like:
As you passed “asa” as country name


MVC Samples for Insert, Update and Delete

1.       Created a model class for country like below;

namespace SampleLibraryApplication.Models
{
    public class Country
    {
       
        public int CountryId { get; set; }

        [DisplayName("Country")]
        [Required(ErrorMessage = "Country Name is Required.")]
        public string CountryName { get; set; }

    }
}

2.       Lets create the controller to display the list items;
It follow the below topics also:

  1. Convert object to json in MVC.
  2. How to Use WebClient to call WebApi
  3. How to call WebApi through Webpage
  4. call web api from mvc controller
  5. How to declare local variable in MVc in Loop


I am using the  WebClient to fetch the result of WebAPI that we publish;

  //
        // GET: /Country/
        public ActionResult Index()
        {
            /// Get the URL of Ur WEbApi which you are refering
            var productDetailUrl = Url.RouteUrl("DefaultApi", new { httproute = "", controller = "CountryDetails" }, Request.Url.Scheme);
            WebClient client1 = new WebClient();

            var result = client1.DownloadString(productDetailUrl);

              /// deserializing the response from WebApi as
            List<Country> model = (JsonConvert.DeserializeObject<List<Country>>(result));

            return View(model);

        }
The URL will form as http://localhost:64622/api/countrydetails/ to access the WebApi.
We will get a response into JSON format and serialize it into Object of Country, As  we are getting the array of object from the response serializing it by List<Country>>;
We will get the list of country which we need to show in view.

3.       Creating the view of strongly type  of  @model List<SampleLibraryApplication.Models.Country>
Code to view the response as;
<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>
                    #
                </th>
                <th>
                    Country Name
                </th>
            </tr>
        </thead>
        <tbody>

            @foreach (var role in Model.Select((x, i) => new { Index = i + 1, value = Model[i] }))
            {
                <tr>
                    <td scope="row"> @role.Index  </td>
                    <td>
                        @role.value.CountryName
                    </td>
                   
                </tr>
            }
        </tbody>
    </table>
</div>
You will see the Output as:


4.       Created a partial view to add and update the records of country. (AddNewCountry.cshtml).
Make it strongly type with country.
AddNewCountry.cshtml
Form for adding the new country details

@model SampleLibraryApplication.Models.Country


<div class="modal-dialog" role="document">

    @using (Html.BeginForm("AddNewCountry", "Country", FormMethod.Post, null))
    {
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                @if (Model.CountryId == 0)
                {
                    <h4 class="modal-title" id="myModalLabel">Add Country</h4>
                }
                else
                {
                    <h4 class="modal-title" id="myModalLabel">Edit Country</h4>

                }

            </div>
            @*<div>
                    <h1>Edit Form Content</h1>
                </div>*@
            <div class="modal-body">
                <div class="form-group">
                    @Html.LabelFor(m => m.CountryName, new { @class = "col-md-2 control-label" })
                    <div class="col-md-10">
                        <div class="input-group">
                            <span class="input-group-addon" id="sizing-addon2">@@</span>
                            @Html.TextBoxFor(o => o.CountryName, new { @class = "form-control" })
                            @*@Html.TextBoxFor(o => o.CountryName)*@
                          

                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-12" style="height:10px"></div>
                @Html.HiddenFor(o => o.CountryId)
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <input type="submit" class="btn btn-primary" value="Submit" />
                </div>
            </div>
    }
</div>


Index.cshtml :
Open the popup to add the new country value;
It covers topics for :

  1. How to create Partial view.
  2. How to call partial View in MVC
  3. How to call web api post Action WebClient
  4. How to call web api Put action WebClient

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Add New Country
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    @Html.Partial("AddNewCountry", new SampleLibraryApplication.Models.Country())
</div>


Controller code for adding new country : It contains both the code for adding and editing the country.

Steps to access the WebApi;
a.       Creating Webclint object.
b.      Passing the credentials
c.       Frame the webapit URL
d.      Calling the webapi with POST  or PUST as it is for insert or Update operation
e.      Getting response at form of JSON
[HttpPost]
        public ActionResult AddNewCountry(Country country)
        {
            string jsonResponse = string.Empty;
            if (country.CountryId == 0)
            {
                // Create string to hold JSON response

                var productDetailUrl = Url.RouteUrl("DefaultApi", new { httproute = "", controller = "CountryDetails" }, Request.Url.Scheme);
                string json = JsonConvert.SerializeObject(country);
// a.
                using (var client = new WebClient())
                {
                    try
                    {
//b.
                        client.UseDefaultCredentials = true;
                        client.Headers.Add("Content-Type:application/json");
                        client.Headers.Add("Accept:application/json");
//c.
                        var uri = new Uri(productDetailUrl);
//d.
                        var response = client.UploadString(uri, "POST", json);

                        jsonResponse = response;
                    }
                    catch (WebException ex)
                    {
                        // Http Error
                        if (ex.Status == WebExceptionStatus.ProtocolError)
                        {
                            HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
                            var statusCode = (int)wrsp.StatusCode;
                            var msg = wrsp.StatusDescription;
                            throw new HttpException(statusCode, msg);
                        }
                        else
                        {
                            throw new HttpException(500, ex.Message);
                        }
                    }
                }
                ViewBag.SaveMessage = "Record Save Successfully"; // Not working as need to pass it to temp data and than pass it to viewbag
            }
            else
            {
                // Create string to hold JSON response
                string url = ApiUrl(country.CountryId);
                string json = JsonConvert.SerializeObject(country);
                using (var client = new WebClient())
                {
                    client.UseDefaultCredentials = true;
                    client.Headers.Add("Content-Type:application/json");
                    client.Headers.Add("Accept:application/json");
                    var uri = new Uri(url);
                    var response = client.UploadString(uri, "PUT", json);
                    jsonResponse = response;

                }
                ViewBag.SaveMessage = "Record Updated Successfully"; // Not working as need to pass it to temp data and than pass it to viewbag
            }


            return RedirectToAction("Index", "Country");

        }

Screen;



5.       Performing delete and Edit operation in Grid;


  1. How to call web api Delete in WebClient.
  2. How to delete record in web api using WebClient
  3. Edit operation in mvc 4 with model pop


Index.cshtml code;
<div class="table-responsive">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>
                    #
                </th>
                <th>
                    Country Name
                </th>
              
            </tr>
        </thead>
        <tbody>

            @foreach (var role in Model.Select((x, i) => new { Index = i + 1, value = Model[i] }))
            {
                <tr>
                    <td scope="row"> @role.Index  </td>
                    <td>
                        @role.value.CountryName
                    </td>
                    <td style="text-align:center">
                        @using (Html.BeginForm("DeleteCountry", "Country", FormMethod.Post, null))
                        {
                            @Html.ActionLink("Delete", "DeleteCountry", new { Id = @role.value.CountryId }, new { @class = "btn btn-primary btn-sm" })
                        }

                    </td>
                    <td >
                        <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal_@role.value.CountryId">
                            Edit
                        </button>
                        <div class="modal fade" id="myModal_@role.value.CountryId" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                            @Html.Partial("AddNewCountry", @role.value)
                          
                        </div>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

Controller Code for deleting the Records using WEbApi Url;
It is follow the same steps just change the code syntax so based on need you can use for your application

        [HttpGet]
        public ActionResult DeleteCountry(int id)
        {

            var webClient = new WebClient();
            webClient.Headers["Content-Type"] = "application/json; charset=utf-8";
            // var productDetailUrl = Url.RouteUrl("DefaultApi", new { httproute = "", controller = "CountryDetails" }, Request.Url.Scheme);
            string url = ApiUrl(id);
            // webClient.req
            string jsonResponse = webClient.UploadString(url, "DELETE", "");
            var response = jsonResponse;

            ViewBag.SaveMessage = "Record Deleted Successfully";
            return RedirectToAction("Index", "Country", null);
        }

    }

public string ApiUrl(object id = null)
        {
            var result = new StringBuilder();
            var productDetailUrl = Url.RouteUrl("DefaultApi", new { httproute = "", controller = "CountryDetails" }, Request.Url.Scheme);
            result.Append(productDetailUrl);
            if (id != null)
                result.Append("/").Append(id.ToString());

            return result.ToString();
        }





No comments:

Post a Comment