Friday, 26 August 2016

Nested Kendo Grid Implementation using Webapi in ASP.NET MVC5

Leave a Comment
In this article we are going to learn about implementing nested kendo grid using angular js and webapi in ASP.NET MVC 5 web application.In previous article we learned about implementing CRUD operations in kendo grid using angular js framework with webapi. If you are new to web api please refer previous posts.
Note:If you are not comfortable with Angular js.You can also implement kendo grid using jquery also please refer Implementing CRUD operations on kendo grid using jquery.Angular kendo grid also internally use jquery for data operations(Retrival,update,delete etc).

Now lets discuss about our new tutorial Nested kendo grid implementation in this article.

Create a Basic Kendo grid using angular js

1.Please refer this previous post link to implement the basic kendo grid(Here i am extending the previous sample application).

2.This is the screen shot of final nested kendo grid.

Nested Kendo Grid Implementation using Webapi
3.I will explain changes i done in step by step..

Add another table to DB

1.Here i created another table "TDetails" to show the nested details for a grid row.
2.Schema definition for TDetails as follows.
CREATE TABLE [dbo].[TDetails] (
    [DetailsID]   INT          IDENTITY (1, 1) NOT NULL,
    [CompanyName] VARCHAR (50) NOT NULL,
    [Salary]      VARCHAR (50) NOT NULL,
    [Location]    VARCHAR (50) NOT NULL,
    [StudentID]   INT          NULL,
    PRIMARY KEY CLUSTERED ([DetailsID] ASC)
);
3.Now click on StudentEntity.edmx file in Models folder.You will get a Entity diagram like below.

Nested Kendo Grid Implementation using Webapi
4.Click on Update Model from Database and add the table you recently created to StudentEntity.edmx.
5.Here i already added the Table.

Nested Kendo Grid Implementation using Webapi

Add a new method to api Controller

1.Add below code to get json data for nested grid.
[HttpGet]
        [Route("StudentDetails/{id}")]
        public HttpResponseMessage GetStudentDetails(int id)
        {
            try
            {
                var studesription = db.TDetails.Where(a => a.StudentID.Equals(id)).ToList();
                return Request.CreateResponse(HttpStatusCode.OK, studesription, Configuration.Formatters.JsonFormatter);

            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.OK, ex.Message, Configuration.Formatters.JsonFormatter);
            }
        }
2.This method gets the data from the api controller based on the StudentID.

Add below extra code to view

3.Add below code to Index view to make kendo nested.
<!--Kendo ui elements-->
    <div id="example" ng-app="KendoGridDemo">
        <h3>CRUD operations on Kendo grid using Angualr JS & webapi</h3>
        <div ng-controller="Controller">
            <kendo-grid k-options="mainGridOptions">
                <!--nested grid template start-->
                <div k-detail-template>
                    <div>
                        <div kendo-grid k-options="subgridOptions(dataItem)">
                        </div>
                    </div>
                </div>
                <!--nested grid template end-->
            </kendo-grid>
        </div>
    </div>
4.I added the nested grid template to the main grid. 5.add below scripting code also to populate the nested grid with data.
//add this code in maingrid options
dataBound: function () {
                        this.expandRow(this.tbody.find("tr.k-master-row").first());
                    },

//nested grid oprtions
$scope.subgridOptions = function (dataItem) {
                    return {
                        dataSource: {
                            type: "json",
                            transport: {
                                read: {
                                    url: "http://localhost:13547/api/TStudentsAPI/StudentDetails/" + dataItem.StudentID,
                                    dataType:"json"
                                }
                            },
                            serverPaging: true,
                            serverSorting: true,
                            serverFiltering: true,
                            pageSize: 5,
                        },
                        scrollable: false,
                        sortable: true,
                        pageable: true,
                        columns: [
                        {
                            field: "DetailsID",
                            title: "DetailsID",
                            width: "180px"
                        },
                        {
                            field: "CompanyName",
                            title: "Company Name",
                            width: "180px"
                        },
                        {
                            field: "Salary",
                            title: "Salary",
                            width: "180px"
                        },
                        {
                            field: "Location",
                            title: "Location",
                            width: "180px"
                        },
                        
                        ]
                    };
6.The complete Index view code after changes is below.

    <!--Kendo style reference files-->
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.flat.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.mobile.min.css" />
    
    <!--kendo script reference files-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>

    <!--Kendo ui elements-->
    <div id="example" ng-app="KendoGridDemo">
        <h3>CRUD operations on Kendo grid using Angualr JS & webapi</h3>
        <div ng-controller="Controller">
            <kendo-grid k-options="mainGridOptions">
                <!--nested grid template start-->
                <div k-detail-template>
                    <div>
                        <div kendo-grid k-options="subgridOptions(dataItem)">
                        </div>
                    </div>
                </div>
                <!--nested grid template end-->
            </kendo-grid>
        </div>
    </div>

    <script>
        //Create a anular app and controller add kendo dependency to app
        angular.module("KendoGridDemo", ["kendo.directives"])
            .controller("Controller", function ($scope) {
                //specify kendo grid options
                $scope.mainGridOptions = {
                    dataSource: {
                        type: "json",   //data type
                        transport: {                          
                            destroy: {
                                url: "api/TStudentsAPI",
                                type: "DELETE"
                            }, read: {
                                url: "http://localhost:13547/api/TStudentsAPI",
                                dataType: "json",
                            },
                            create:
                            {
                                url: "http://localhost:13547/api/TStudentsAPI",
                                type: "POST"
                            },
                            update:
                            {
                                url: "api/TStudentsAPI",
                                type: "PUT",                               
                                parameterMap: function (options, operation) {
                                    if (operation !== "read" && options.models) {
                                        return {
                                            models: kendo.stringify(options.models)
                                        };
                                    }
                                }
                            },
                        },
                        schema: //schema of the table data
                                 {
                                     model:
                                     {
                                         id: "StudentID",
                                         fields: {
                                             StudentID: { editable: false, nullable: false, type: "number" },
                                             FullName: { editable: true, nullable: true, type: "string" },
                                             Contact: { editable: true, nullable: true, type: "number" },
                                             Country: { editable: true, nullable: true, type: "string" },
                                             Designation: { editable: true, nullable: true, type: "string" }
                                         }
                                     }
                                 },
                        pageSize: 5,
                        serverPaging: true,
                        serverSorting: true
                    },
                    editable: "popup",      //editable type popup/inline/batch
                    toolbar: ["create"],    //toolbar options
                    sortable: {
                        mode: "single",  //sorting
                        allowUnsort:true
                    },        
                    pageable: {          //paging
                        buttonCount: 5
                    },        
                    resizeable: true,       //resizing
                    scrollable: false,
                    dataBound: function () {
                        this.expandRow(this.tbody.find("tr.k-master-row").first());
                    },
                    //specify columns that you want to display 
                    columns: [{
                        field: "StudentID",
                        title: "Student ID",
                        width: "180px"
                    },
                    {
                        field: "FullName",
                        title: "FullName",
                        width: "180px"
                    },
                    {
                        field: "Contact",
                        title: "Contact",
                        width: "180px"
                    },
                    {
                        field: "Country",
                        title: "Country",
                        width: "180px"
                    },
                    {
                        field: "Designation",
                        title: "Designation",
                        width: "180px"
                    },
                    //actions columns contains-- edit/delete 
                        {
                            title:"Actions",
                            command: ["edit",
                            {
                                name: "destroy",
                                text: "Delete",
                                width: "120px"
                            }
                            ],
                        }
                    ]
                };
                $scope.subgridOptions = function (dataItem) {
                    return {
                        dataSource: {
                            type: "json",
                            transport: {
                                read: {
                                    url: "http://localhost:13547/api/TStudentsAPI/StudentDetails/" + dataItem.StudentID,
                                    dataType:"json"
                                }
                            },
                            serverPaging: true,
                            serverSorting: true,
                            serverFiltering: true,
                            pageSize: 5,
                        },
                        scrollable: false,
                        sortable: true,
                        pageable: true,
                        columns: [
                        {
                            field: "DetailsID",
                            title: "DetailsID",
                            width: "180px"
                        },
                        {
                            field: "CompanyName",
                            title: "Company Name",
                            width: "180px"
                        },
                        {
                            field: "Salary",
                            title: "Salary",
                            width: "180px"
                        },
                        {
                            field: "Location",
                            title: "Location",
                            width: "180px"
                        },
                        
                        ]
                    };
                };
            });
    </script>
7.Now run the application and see the output in browser.It will be like first image above.

Download source code for this application here Source Code(VS2015 code) .

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Thursday, 25 August 2016

CRUD operations in Kendo grid using angular js and webapi

4 comments
This article will help you to implement CRUD operations on kendo grid using angular js.And i used webapi as data source for this application.In previous webapi  tutorials we saw the basic things like uploading files to web api,posting data to web api,Retriving and displaying web api data on html page.In this tutorial i am we will create kendo grid(a commercial API tool for web  designing). Previously i  implemented kendo grid using Jquery in this blog refer this link Kendo grid using Jquery.Now in present tutorial i am going to implement grid using Angular js.
This article flow as follows:
  1. Creating a ASP.NET Web api application,
  2. Creating a controller to display the grid(View),
  3. Include kendo reference files to View.
  4. Implement CRUD operations on grid. 

Creating a ASP.NET Web API application(Data Source)

1.Create a ASP.NET MVC application by picking a Empty MVC template.

CRUD operations in Kendo grid using angular js and webapi
2.Right click on App_Data folder and add Sql server to the project and create table schema as follows.
3.Data base code is as follows.
---Table Schema
CREATE TABLE [dbo].[TStudent] (
    [StudentID]   INT          IDENTITY (1, 1) NOT NULL,
    [FullName]    VARCHAR (50) NOT NULL,
    [Contact]     BIGINT       NOT NULL,
    [Country]     VARCHAR (50) NOT NULL,
    [Designation] VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([StudentID] ASC)
);
---Insert some data into table
SET IDENTITY_INSERT [dbo].[TStudent] ON
INSERT INTO [dbo].[TStudent] ([StudentID], [FullName], [Contact], [Country], [Designation]) VALUES (1, N'Raviteja', 934348384, N'India', N'software trainee')
INSERT INTO [dbo].[TStudent] ([StudentID], [FullName], [Contact], [Country], [Designation]) VALUES (2, N'avinash', 903983473, N'china', N'trainee')
INSERT INTO [dbo].[TStudent] ([StudentID], [FullName], [Contact], [Country], [Designation]) VALUES (3, N'Rajk', 938483746, N'Canada', N'senior')
SET IDENTITY_INSERT [dbo].[TStudent] OFF

4.Add ADO.NET Entity Data Model to the project.
Note: In every sample project i am creating a ADO.DOT NET Entity Data Model.Because it automatically generates necessary files like Model objects,Connection string and Context Class required for project.

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Create API Controller

1.Right click on Controllers --> Add --> Controller --> select web api Controller with method generated by Entity framework(Before this build solution once).
2.Select Model class and data context class.

CRUD operations in Kendo grid using angular js and webapi
3.Click add then visual studio automatically create scaffolding code with actions.
4.The generated code is as follows.


namespace AngularKendoGrid.Controllers
{
    public class TStudentsAPIController : ApiController
    {
        private StudentDBEntities db = new StudentDBEntities();

        // GET: api/TStudentsAPI
        public IQueryable GetTStudents()
        {
            return db.TStudents;
        }

        // GET: api/TStudentsAPI/5
        [ResponseType(typeof(TStudent))]
        [HttpGet]
        public async Task GetTStudent(int id)
        {
            TStudent tStudent = await db.TStudents.FindAsync(id);
            if (tStudent == null)
            {
                return NotFound();
            }

            return Ok(tStudent);
        }

        // PUT: api/TStudentsAPI/5
        [ResponseType(typeof(void))]
        [HttpPut]
        public async Task PutTStudent( TStudent tStudent)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //if (id != tStudent.StudentID)
            //{
            //    return BadRequest();
            //}

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

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TStudentExists(tStudent.StudentID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/TStudentsAPI
        [ResponseType(typeof(TStudent))]
        [HttpPost]
        public async Task PostTStudent(TStudent tStudent)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.TStudents.Add(tStudent);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = tStudent.StudentID }, tStudent);
        }

        // DELETE: api/TStudentsAPI/5
        [ResponseType(typeof(TStudent))]
        [HttpDelete]
        public async Task DeleteTStudent(TStudent student)
        {
            TStudent tStudent = await db.TStudents.FindAsync(student.StudentID);
            if (tStudent == null)
            {
                return NotFound();
            }

            db.TStudents.Remove(tStudent);
            await db.SaveChangesAsync();

            return Ok(tStudent);
        }

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

        private bool TStudentExists(int id)
        {
            return db.TStudents.Count(e => e.StudentID == id) > 0;
        }
    }
}
5.Here i changed two methods parameters here
 public async Task DeleteTStudent(TStudent student)
{
}

 public async Task PutTStudent( TStudent tStudent)
{
}
6.Here for both methods there is a parameter int id.I removed it because kendo grid only sends the object data.
Note: compare the above code with the code generated by scaffolding and check.Then you will understand the changes easily by comparing.

Create a Controller and add Index action

1.Create another MVC controller and add View Index action to display the grid.
2.Add below  kendo reference files to Index view.
    <!--Kendo style reference files-->
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.flat.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.mobile.min.css" />
    
    <!--kendo script reference files-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>
3.The complete View code with Angular script is as follows.


    <!--Kendo style reference files-->
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.flat.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.mobile.min.css" />
    
    <!--kendo script reference files-->
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/angular.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/jszip.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2016.1.412/js/kendo.all.min.js"></script>

    <!--Kendo ui elements-->
    <!--Here k-options is kendo angular directive-->
    <div id="example" ng-app="KendoGridDemo">
        <h3>CRUD operations on Kendo grid using Angualr JS & webapi</h3>
        <div ng-controller="Controller">
            <kendo-grid k-options="mainGridOptions">
            </kendo-grid>
        </div>
    </div>

    <script>
        //Create a anular app and controller add kendo dependency to app
        angular.module("KendoGridDemo", ["kendo.directives"])
            .controller("Controller", function ($scope) {
                //specify kendo grid options
                $scope.mainGridOptions = {
                    dataSource: {
                        type: "json",   //data type
                        transport: {                          
                            destroy: {
                                url: "api/TStudentsAPI",
                                type: "DELETE"
                            }, read: {
                                url: "api/TStudentsAPI",    //http://localhost:13547/
                                dataType: "json",
                            },
                            create:
                            {
                                url: "api/TStudentsAPI",    //http://localhost:13547/
                                type: "POST"
                            },
                            update:
                            {
                                url: "api/TStudentsAPI",
                                type: "PUT",                               
                                parameterMap: function (options, operation) {
                                    if (operation !== "read" && options.models) {
                                        return {
                                            models: kendo.stringify(options.models)
                                        };
                                    }
                                }
                            },
                        },
                        schema: //schema of the table data
                                 {
                                     model:
                                     {
                                         id: "StudentID",
                                         fields: {
                                             StudentID: { editable: false, nullable: false, type: "number" },
                                             FullName: { editable: true, nullable: true, type: "string" },
                                             Contact: { editable: true, nullable: true, type: "number" },
                                             Country: { editable: true, nullable: true, type: "string" },
                                             Designation: { editable: true, nullable: true, type: "string" }
                                         }
                                     }
                                 },
                        pageSize: 5,
                        serverPaging: true,
                        serverSorting: true
                    },
                    editable: "popup",      //editable type popup/inline/batch
                    toolbar: ["create"],    //toolbar options
                    sortable: {
                        mode: "single",  //sorting
                        allowUnsort:true
                    },        
                    pageable: {          //paging
                        buttonCount: 5
                    },        
                    resizeable: true,       //resizing
                    scrollable: false,
                    //specify columns that you want to display 
                    columns: [{
                        field: "StudentID",
                        title: "Student ID",
                        width: "180px"
                    },
                    {
                        field: "FullName",
                        title: "FullName",
                        width: "180px"
                    },
                    {
                        field: "Contact",
                        title: "Contact",
                        width: "180px"
                    },
                    {
                        field: "Country",
                        title: "Country",
                        width: "180px"
                    },
                    {
                        field: "Designation",
                        title: "Designation",
                        width: "180px"
                    },
                    //actions columns contains-- edit/delete 
                        {
                            title:"Actions",
                            command: ["edit",
                            {
                                name: "destroy",
                                text: "Delete",
                                width: "120px"
                            }
                            ],
                        }
                    ]
                };
            });
    </script>
4.Now finally run the application and see the output..

CRUD operations in Kendo grid using angular js and webapi
Edit operation:
CRUD operations in Kendo grid using angular js and webapi
Delete:
CRUD operations in Kendo grid using angular js and webapi

Download the source code of this application here Source code(VS2015).

Conclusion

I hope this tutorial is understandable and useful for every reader.Please comment if you suggest any modification to improve the quality of article.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Wednesday, 24 August 2016

How to upload files to webapi using jquery

Leave a Comment
Welcome to next part of tutorial in wepapi series.In this post i am going to explain about How to upload files using web api service with help of jquery. If you are new to web api in ASP.NET MVC5 please refer the below posts for basics of WEBAPI.
Introduction to WEBAPI
How to fetch and display data from webapi in ASP.NET MVC5
How to post data to webapi using jquery client

Create a api service to save the uploaded file in server

1.I created a UploadapiController api controller.
2.Added a new folder "UploadFiles" folder to the solution.
3.Replace the UploadapiControlller code with the below code for saving the uploaded file.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WebApiExample.Controllers
{
    public class UploadapiController : ApiController
    {
        public Task Post()
        {
            List savedFilePath = new List();
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
            var provider = new MultipartFileStreamProvider(rootPath);
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(t =>
                {
                    if (t.IsCanceled || t.IsFaulted)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }
                    foreach (MultipartFileData item in provider.FileData)
                    {
                        try
                        {
                            string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                            string newFileName = Guid.NewGuid() + Path.GetExtension(name);
                            File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));

                            Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
                            string fileRelativePath = "~/UploadedFiles/" + newFileName;
                            Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
                            savedFilePath.Add(fileFullPath.ToString());
                        }
                        catch (Exception ex)
                        {
                            string message = ex.Message;
                        }
                    }

                    return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
                });
            return task;
        }
    }
}

Add Controller to display the Index(Fileupload element)

1.Right click on Controllers folder --> Add --> Controller --> select empty controller template -->name it.
public class UploadController : Controller
    {
        // GET: Upload
        public ActionResult Index()
        {
            return View();
        }
    }
2.Now add view to this action method to display the UI.
3.Replace Index view code with the below View code.
@{
    ViewBag.Title = "www.mitechdev.com";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<h2>File upload to webapi</h2>

<div class="panel panel-info">
    <div class="panel-heading">
        File upload in webapi
    </div>
    <div class="panel-body">
        <div class="form-group">
            <input type="file" id="uploadfile" />
        </div>
        <input id="btnSubmit" class="btn btn-default" type="button" value="Upload" />
        <div class="text-info" id="status"></div>
    </div>
</div>

<script>
            $(document).ready(function () {
                $('#btnSubmit').click(function () {
                    if ($('#uploadfile').val() == '') {
                        alert('Please select file');
                        return;
                    }

                    var formData = new FormData();
                    var file = $('#uploadfile')[0];
                    formData.append('file', file.files[0]);
                    $.ajax({
                        url: 'http://localhost:28335/api/Uploadapi',
                        type: 'POST',
                        data: formData,
                        contentType: false,
                        processData: false,
                        success: function (d) {                     
                            $("#status").html("<span>File uploaded here: <a class='text-success' href="+d+">Open File</a></span>");
                            $('#uploadfile').val(null);
                        },
                        error: function () {
                            alert("Faild please try upload again");
                        }
                    });
                });
            });
</script>
4.Here i created a object to FormData() and posted the file to the api controller.
5.run the application and See the out put in browser.

6.After uploading the file you can see the file by clicking on the below Link "Open".
7.Here in this sample application i uploaded a sample txt file.we can see this by clicking Open...

Download the source code for this tutorial here..Source Code(Visual studio2015 code).

Conclusion

I hope this tutorial is understandable and useful for every reader.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Friday, 19 August 2016

How to post data to webapi using Jquery in ASP.NET MVC5

Leave a Comment
Welcome to next part of tutorial in wepapi series.In this post i am going to explain about How to post and save the user entered data in database using web api service. If you are new to web api in ASP.NET MVC5 please refer the below posts for basics of WEBAPI.
Introduction to WEBAPI
How to fetch and display data from webapi in ASP.NET MVC5
Now lets begin our tutorial..

Create Visual studio application

1.Create a ASP.NET Web application(visual studio 2013 or 2015) using Empty MVC template.
2.It is a great idea to start any application using Empty template because there is more scope for learning and implementing every thing from scratch(not for production).
3.Now our solution contains basic MVC project structure.
4.Add a Database to the App_Data folder (by right click App_Data folder --> Add --> New Item --> Select Sql Data base under Data section --> name it --> Add.
5.Create a table in data base with below code.
CREATE TABLE [dbo].[Student] (
    [StudentID]   INT          NOT NULL,
    [StudentName] VARCHAR (50) NOT NULL,
    [Email]       VARCHAR (50) NOT NULL,
    [City]        VARCHAR (50) NULL,
    [Contact]     BIGINT       NULL,
    [Country]     VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([StudentID] ASC)
);

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.
4.Now Model is added to my project.
Note: Now we have to create a Webapi controller for that this article will help you to setup webapi in your application Introduction to WebAPI in ASP.NET MVC 5

Web api controller to Application

1.Replace the code of webapi controller with below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using PostingDatainWebAPI.Models;

namespace PostingDatainWebAPI.Controllers
{
   public class StudentAPIController : ApiController
    {
        public HttpResponseMessage Post(Student student)
        {
            HttpResponseMessage result;
            if (ModelState.IsValid)
            {
                using (StudentDataBaseEntities db = new StudentDataBaseEntities())
                {
                    db.Students.Add(student);
                    db.SaveChanges();                   
                }
                result = Request.CreateResponse(HttpStatusCode.Created, student);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest, "Server failed to save data");
            }
             return result;
        }
    }
}

Create a User form page to input some data

1.Here client is simple View page(Index .cshtml page from PostController) .
2.Create a Controller by right clicking on Controllers folder --> i named it as PostController.
3.I created Index action method and added view with Index.cshtml name.
//Using Jquery
        public ActionResult Index()
        {
            return View();
        }
4.In this View i added a simple jquery ajax method to post data to web api service.
5.Replace the Index view code with below code.

@{
    ViewBag.Title = "Posting Data to WEBAPI using Jquery";
}

<h3 class="text-info">Posting Data to WEBAPI using Jquery</h3>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<style>
    input{
        max-width:250px;
    }
</style>
<h5 class="text-danger"><b>Note:</b>Please Enter all details correctly and submit
    Here i did not applied validations to this form</h5>
 <div class="container">
     <form name="postform" id="postform" class="form-horizontal">
            <div class="form-group">
                <label class="text-info">Student ID</label>
                <input type="number" id="txtStudentID" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Student Name</label>
                <input type="text" id="txtStudentName" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Email</label>
                <input type="email" id="txtEmail" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">City</label>
                <input type="text" id="txtCity" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Contact Number</label>
                <input type="number" id="txtContact" class="form-control" />
            </div>
            <div class="form-group">
                <label class="text-info">Country</label>
                <input type="text" id="txtCountry" class="form-control" />
            </div>

            <button type="submit" class="btn btn-default">Save</button>
     </form>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $("#postform").submit(function (e) {
            e.preventDefault();
            var apiurl = "http://localhost:9627/api/StudentAPI";
            var data = {
                StudentID: $("#txtStudentID").val().trim(),
                StudentName: $("#txtStudentName").val().trim(),
                Email: $("#txtEmail").val().trim(),
                City: $("#txtCity").val().trim(),
                Contact: $("#txtContact").val().trim(),
                Country: $("#txtCountry").val().trim(),
            }
            $.ajax({
                url: apiurl,
                type: 'POST',
                dataType: 'json',
                data: data,
                success: function (d) {
                    alert("Saved Successfully");
                    document.getElementById("postform").reset();
                },
                error: function () {
                    alert("Error please try again");
                }
            });
        });
    });

</script>
Note: For this form i did not implemented client side validation.
6.Here simply i am reading the form values using jquery.and posting form values to web api for saving on database.
7.the output of the application is..

8.After saving data on server you will get a message like this..

Download the source code of this application here.. Source Code(Visual studio 2015 code)

Conclusion

I hope this tutorial is understandable and useful for every reader.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].


Wednesday, 10 August 2016

How to Fetch and display data from WEBAPI in ASP.NET MVC

3 comments
Hi every one in this article i am going to explain "How to Fetch and Display data from WebAPI in ASP.NET MVC application".Before going to read this post refer Implementation of WEBAPI in ASP.NET MVC. Without wasting anytime i going for implementation steps.
In this application i implemented two ways to get and display the data in ASP.NET MVC application.
1.Using Jquery Client
   We can access web api data using jquery with a simple ajax method.
2.Using HttpClient object(in controller level)
   HttpClient object enables us to get the web api data using simple string.

Create Visual studio application

1.Create a ASP.NET Web application(visual studio 2013 or 2015) using Empty MVC template.
2.It is a great idea to start any application using Empty template because there is more scope for learning and implementing every thing from scratch(not for production).
3.Now our solution contains basic MVC project structure.
4.Add a Database to the App_Data folder (by right click App_Data folder --> Add --> New Item --> Select Sql Data base under Data section --> name it --> Add.
5.Create a table in data base with below code.
 
---Table Schema
CREATE TABLE [dbo].[UserTable] (
    [UserID]   INT          IDENTITY (1, 1) NOT NULL,
    [FullName] VARCHAR (50) NOT NULL,
    [Email]    VARCHAR (50) NOT NULL,
    [Contact]  BIGINT       NOT NULL,
    [Address]  VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([UserID] ASC)
);
---Insert data into table
SET IDENTITY_INSERT [dbo].[UserTable] ON
INSERT INTO [dbo].[UserTable] ([UserID], [FullName], [Email], [Contact], [Address]) VALUES (1, N'Raviteja', N'raviteja.s@gmail.com', 90347847378, N'Hyderabad')
INSERT INTO [dbo].[UserTable] ([UserID], [FullName], [Email], [Contact], [Address]) VALUES (2, N'Thomas', N'thomas.m@gmail.com', 90038394384, N'Chennai')
INSERT INTO [dbo].[UserTable] ([UserID], [FullName], [Email], [Contact], [Address]) VALUES (3, N'Rajkumar', N'rajk@gmail.com', 90374834837, N'Bangalore')
INSERT INTO [dbo].[UserTable] ([UserID], [FullName], [Email], [Contact], [Address]) VALUES (4, N'ramgopal varma', N'gopalr@gmail.com', 90384873784, N'Mumbai')
SET IDENTITY_INSERT [dbo].[UserTable] OFF

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.
4.Now Model is added to my project.

Add Web api controller to Application

1.Right click on Controllers --> Add --> Controller --> Select Empty web api controller --> name it.
2.Replace the api controller code with below code.
Note: After adding api controller to project do not forget to add below namespace to Global.asax file
using System.Web.Http;
using System.Web.Routing;
3.And add below line of code in Application_start method for webapi configuration globally.
GlobalConfiguration.Configure(WebApiConfig.Register);
4.For more details refer Introduction to WebAPI in ASP.NET MVC 5

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

namespace DisplayingDataFromWebAPI.Controllers
{
    public class WebAPIController : ApiController
    {
        //api get method.
        public HttpResponseMessage Get()
        {
            using (WebAPIDBEntities db = new WebAPIDBEntities())
            {
                List userlist = new List();
                userlist = db.UserTables.OrderBy(a => a.UserID).ToList();
                HttpResponseMessage response;
                response = Request.CreateResponse(HttpStatusCode.OK,userlist);
                return response;
            }
        }
    }
}
5.In above code i am retrieving data from database and returning using HttpResponseMessage action.
6.Now we created HTTP service successfully.Now our step is to consume the service on client side.

Consuming webapi service using Jquery

1.Here client is simple View page(cshtml page).
2.Create a Controller by right clicking on Controllers folder --> i named it as HomeController.
3.I created Index action method and added view with Index.cshtml name.
//Using Jquery
        public ActionResult Index()
        {
            return View();
        }
4.In this View i added a simple jquery ajax method to get and display the data.
5.Replace the Index view code with below code.
@{
    ViewBag.Title = "Fetching data from Server";
}
<h2>WebAPI Example part1</h2>

<script src="~/Scripts/jquery-1.9.1.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        var uri = 'http://localhost:47495/api/WebAPI';
        $("#btnLoad").click(function () {
            $.ajax({
                url: uri,
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    //debugger;
                    //I am creating table using jquery
                    var table = $("<table/>").addClass("table table-responsive table-bordered");
                    var header = $("<thead/>").html("<tr><th>UserID</th><th>FullName</th><th>Email</th><th>Contact</th><th>Address</th>");
                    table.append(header);
                    $.each(data, function (i,val) {
                        var row = $("<tr/>");
                        row.append($("<td/>").html(val.UserID));
                        row.append($("<td/>").html(val.FullName));
                        row.append($("<td/>").html(val.Email));
                        row.append($("<td/>").html(val.Contact));
                        row.append($("<td/>").html(val.Address));
                        table.append(row);
                    });
                    $("#diplayPanel").html(table);
                },
                error: function () {
                    alert("An error occured while getting data");
                }
            });
        });
    });
</script>

<div>
    <input type="button" class="btn btn-success" value="Load Data from API" id="btnLoad" />
    <br/><br/>
    <div id="diplayPanel"></div>
</div>

using HttpClient

1.Create another Controller in HomeController.
2.The complete HomeController code is as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DisplayingDataFromWebAPI.Models;
using System.Net.Http;

namespace DisplayingDataFromWebAPI.Controllers
{
    public class HomeController : Controller
    {
        //Using Jquery
        public ActionResult Index()
        {
            return View();
        }
        //using HttpClient
        public ActionResult HttpClientView()
        {
            List lstUser = new List();
            HttpClient client = new HttpClient();
            var result = client.GetAsync("http://localhost:47495/api/WebAPI").Result;
            if (result.IsSuccessStatusCode)
            {
                lstUser = result.Content.ReadAsAsync>().Result;
            }
            return View(lstUser);
        }
    }
}
3.Here in Httpclient object get the data from wepapi asynchronously.And i am passing data to view with concept of strongly typed view.(using model directive).
4.Add view to HttpClientView action method.
5.Replace the code of view with below code.
@model IEnumerable<DisplayingDataFromWebAPI.Models.UserTable>
@{
    ViewBag.Title = "Web API part 2";
}

<h2>Displaing Web API data using HttpClient</h2>
<div>
    <table class="table table-responsive table-bordered">
        <thead>
            <tr>
                <th>UserID</th>
                <th>Full Name</th>
                <th>Email</th>
                <th>Contact</th>
                <th>Address</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var i in Model)
            {
                <tr>
                    <td>@i.UserID</td>
                    <td>@i.FullName</td>
                    <td>@i.Email</td>
                    <td>@i.Contact</td>
                    <td>@i.Address</td>
                </tr>
            }
        </tbody>
    </table>
</div>
6.Finally we get the output for two methods like below.
Using Jquery


How to Fetch and display data from WEBAPI in ASP.NET MVC
when we click on button the below table is displayed by getting data from api.
Using HttpClient


How to Fetch and display data from WEBAPI in ASP.NET MVC

Download source code this application here Source code(VS2015 code).

Conclusion

I hope this tutorial is understandable and useful for every reader.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].


Tuesday, 2 August 2016

Implementing MVC GRID in ASP.NET MVC application

Leave a Comment
Hi every one in previous post i explained about How to Install MVCGrid in ASP.NET MVC application using both manual and Nuget package installation.In this post i am going to explain about Implementing Basic MVCGrid.Before get started with this tutorial refer above link to understand the installation of MVCGrid in ASP.NET MVC web application.

Implementing MVC GRID in ASP.NET MVC

1.Create a Visual studio application(Visual studio 2013 or 2015 are recommended because MVCGrid supports MVC3 or higher versions of ASP.NET MVC frameworks).
2.Take MVC template from Visual studio builtin templates to develop web application.
3.As usual create Table and insert some data in Data Base(SqlExpress LocalDB).
4.DB code i used for table schema is..
---For Table Schema
CREATE TABLE [dbo].[Customer] (
    [CustomerId] INT          IDENTITY (1, 1) NOT NULL,
    [FirstName]  VARCHAR (50) NOT NULL,
    [LastName]   VARCHAR (50) NOT NULL,
    [OrderDate]  DATE         NOT NULL,
    [Status]     VARCHAR (50) NOT NULL,
    PRIMARY KEY CLUSTERED ([CustomerId] ASC)
);
---Insert some data into table
SET IDENTITY_INSERT [dbo].[Customer] ON
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (1, N'Raviteja', N'Swayampu', N'2016-12-12', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (2, N'venkatesh ', N'Malli', N'2016-02-03', N'Inactive')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (3, N'Martin ', N'Lutherking', N'2016-03-04', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (4, N'Abhraham ', N'Lincon', N'2016-04-03', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (5, N'Jarj', N'Bush', N'2016-05-03', N'Inactive')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (6, N'Bharak', N'Obama', N'2016-07-03', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (7, N'Hillay ', N'Clinton', N'2016-08-02', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (8, N'Bill ', N'Clinton', N'2016-09-02', N'Inactive')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (9, N'Nepolian', N'Hill', N'2016-01-01', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (10, N'Michal ', N'Farady', N'2016-05-03', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (11, N'Thomas ', N'Edison', N'2016-05-31', N'Inactive')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (12, N'Mark ', N'Twain', N'2016-05-23', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (13, N'Robert', N'Kiosaki', N'2016-09-30', N'Active')
INSERT INTO [dbo].[Customer] ([CustomerId], [FirstName], [LastName], [OrderDate], [Status]) VALUES (14, N'JK', N'Rollings', N'2016-03-14', N'Active')
SET IDENTITY_INSERT [dbo].[Customer] OFF
5.Now the data base side is completed.

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.
4.Now Model is added to my project.

Implement Grid Definition in MVCGridConfig.cs

1.Go to App_Start folder --> replace MVCGridConfig.cs file with below code.(Grid configuration)
Note: Make sure that you had MVCGrid Installed in your application.You do not refer Installing MVCGrid


[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MVCGrid.MVCGridConfig), "RegisterGrids")]
namespace MVCGrid
{
    using System.Collections.Generic;
    using MVCGrid.Models;
    using MVCGrid.Web;
    using System;
    using System.Linq;
    public static class MVCGridConfig 
    {
        public static void RegisterGrids()
        {          
            MVCGridDefinitionTable.Add("SampleGrid", new MVCGridBuilder()
                .WithAuthorizationType(AuthorizationType.AllowAnonymous)
                .AddColumns(cols =>
                {
                    // Add your columns here
                    cols.Add().WithColumnName("CustomerId")
                        .WithHeaderText("CustomerId")
                        // use the Value Expression to return the cell text for this column
                        .WithValueExpression(i => i.CustomerId.ToString()); 
                    cols.Add().WithColumnName("FirstName")
                        .WithHeaderText("FirstName")
                        .WithValueExpression(i => i.FirstName);
                    cols.Add().WithColumnName("LastName")
                        .WithHeaderText("LastName")
                        .WithValueExpression(i => i.LastName);
                    //Hiding Visibility of Column
                    cols.Add().WithColumnName("FullName")
                        .WithHeaderText("Full Name")
                        .WithValueTemplate("{Model.FirstName}{Model.LastName}")
                        .WithVisibility(visible: false, allowChangeVisibility: true)
                        .WithSorting(false);
                    cols.Add().WithColumnName("OrderDate")
                        .WithHeaderText("OrderDate")
                        .WithValueExpression(i => i.OrderDate.ToString());
                    cols.Add().WithColumnName("Status")
                        .WithHeaderText("Status")
                        .WithValueExpression(i => i.Status);                   
                })
                .WithRetrieveDataMethod((context) =>
                {
                    //Data source for MVCGrid
                    var ItemList = new QueryResult();
                    using (DatabaseEntities db=new DatabaseEntities())
                    {
                        ItemList.Items = db.Customers.ToList();
                    }
                    return ItemList;
                })
            );            
        }
    }
}
2.I added name space to import functionality of MVCGrid.
using MVCGrid.Web;
3.I had given name as SampleGrid.using this i will call it in View page where i want to display Grid.
4.I bind the data source for grid in .WithRetrieveDataMethod like below.
              .WithRetrieveDataMethod((context) =>
                {
                    //Data source for MVCGrid
                    var ItemList = new QueryResult();
                    using (DatabaseEntities db=new DatabaseEntities())
                    {
                        ItemList.Items = db.Customers.ToList();
                    }
                    return ItemList;
                })
5.we must pass the data to grid using QueryResult object.(I binded the data to ItemList QueryResult object).

Create Controller and Index action

1.Add Controller and name it .
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
2.Create Index action method and add View to Index action method.
3.Replace the Index View code with below code.
<!--Add MVCGrid reference to view-->
@using MVCGrid.Web;
@{
    ViewBag.Title = "www.mitechdev.com";
}

<h2>MVC GRID in ASP.NET MVC5 Web application</h2>
<!--Call grid using name specified in MVCGridConfig.cs-->
@Html.MVCGrid("SampleGrid")
4.Now run the application and see the output ..

Implementing MVC GRID in ASP.NET MVC application

Multiple Grid Configuration

1.If your application contains number of grids.To set the default configuration for all grids Create a GridDefaults object and set the desired properties in it.
2.Check the below code for setting default properties for multiple grids.
//Default settings 
GridDefaults defaultSet1 = new GridDefaults()
{
    Paging = true,
    ItemsPerPage = 20,
    Sorting = true,
    NoResultsMessage = "Sorry, no results were found"
};
//sample grid
MVCGridDefinitionTable.Add("UsageExample",
    new MVCGridBuilder(defaultSet1) // pass in defaults object to ctor
    .AddColumns(cols =>
    {
        // add columns
    })
    .WithRetrieveDataMethod((context) =>
    {
        //get data
        return new QueryResult();
    })
);
Download source code for this application Source Code(Visual Studio 2015 code)

Conclusion

I hope this tutorial is understandable for every reader.In next post i will explain about Implementation of MVCGrid in ASP.NET MVC application.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

Getting started with MVC GRID

Leave a Comment
For now we discussed on many Grids that are used by many number of developers across globe.In this tutorial i am going to introduce MVC Grid  that is only created to help ASP.NET MVC developers and as well as companies because it comes with open source license(not like kendogrid as licensed one). Implementation of this MVCGrid is very easy.

MVC GRID

A grid for ASP.NET MVC and Bootstrap with ajax paging and sorting. Also has filtering support, export to CSV back button support, and graceful degradation.You can add it to your project very easily and get it running with minimal effort, but it also has the extensibility to customize when needed.
To learn more about MVCGRID.NET visit official site mvcgrid.net.And for support on this product refer below link. 
https://github.com/joeharrison714/MVCGrid.Net/issues
Note: There are other open source grid plugins i explained here Jquery Grid,Angular Grid(for angular applications,Jquery Data Tables and Web Grid helper for ASP.NET MVC applications).

Prerequisites for MVC GRID

1.ASP.NET MVC 3 or higher versions.
2.Jquery plugin.
3.Twitter Bootstrap framework
Note: You can use either Twitter Bootstrap or Your own styles for grid.

Features of MVC GRID

  • Uses your existing model objects for data
  • Server-side sorting and paging using AJAX
  • updates query string to support maintaining grid state when navigating back
  • gracefully degrades on older browsers (Ex: IE8)
  • Built-in exporting to CSV.
  • Filtering and column visibility support with minimal client-side code.
Basic MVC GRID look like below.

Getting started with MVC GRID in ASP.NET MVC 5 web application

Installing MVC GRID in ASP.NET MVC application

We can install MVC GRID in ASP.NET MVC Web application in two ways.
Using Nuget Package
1.Install using Nuget package Manager console --> Go To Menu --> Tools --> Nuget package manager --> Package manager console
2.Paste below command and press enter.
PM> Install-Package MVCGrid.Net 
################################ or ###################################
1.Go to solution explorer --> Right click on project name --> Manage Nuget Packages -->search for "mvcgrid".

Getting started with MVC GRID in ASP.NET MVC 5 web application

2.Install MVCGrid.Net..
3.Add the javascript reference to your _Layout page after jquery is referenced
<!-- add this after jquery reference -->
<script src="~/MVCGridHandler.axd/script.js"></script>
4.Add your grid definitions to the RegisterGrids method in the MVCGridConfig file under the App_Start folder.
5.Use the grids in your view by adding the using @using MVCGrid.Web and then the html helper @Html.MVCGrid("YourGridName") 

Note:If you follow above two steps there is no need to configure anything for MVCGrid in web application.Here i am also sharing Manual installation also(Developers prefer this because the code used should not create problems for previous project code).

Manual Installation
1.In manual installation process add MVCGrid.dll.
2.Create a file called MVCGridConfig.cs under the App_Start folder.
3.Replace code with below code.
using MVCGrid.Web;
public class MVCGridConfig
{
    public static void RegisterGrids()
    {
 //All grid definitions are goes here.
        // add your Grid definitions here
 //using the MVCGridDefinitionTable.Add method
    }
}
4.Add the following line to Global.asax in the Application_Start() method
MVCGridConfig.RegisterGrids();
5Add the following to your web.config file.
<system.webServer>
    <handlers>
      <add name="MVCGridHandler" verb="*" path="MVCGridHandler.axd" type="MVCGrid.Web.MVCGridHandler, MVCGrid" />
    </handlers>
  </system.webServer>
6.Add the java script reference to your _Layout page after jquery plugin is referenced.
<!-- add this after jquery reference -->
<script src="~/MVCGridHandler.axd/script.js"></script>
7.Finally use the grids in your view by adding the using @using MVCGrid.Web and then the html helper @Html.MVCGrid("YourGridName") 

Conclusion

I hope this tutorial is understandable for every reader.In next post i will explain about Implementation of MVCGrid in ASP.NET MVC application.If you are not subscribed to this blog subscribe.follow on Social networks for daily awesome updates[Facebook,twitter,google plus].


Monday, 1 August 2016

How to Delete Multiple Records in Webgrid using Checkboxes in MVC5

Leave a Comment
In this post i am going to explain How to implement Multiple records deletion using Check boxes in ASP.NET MVC5 application.In previous post i implemented  Exporting Web grid to PDF page and nested web grid .
Now lets begin the implementation of Multi row delete web grid in ASP.NET MVC5 application in step by step process.

Implementation

Create a Visual application and add Table

1.Create a Visual studio web application and add Sql server(Local DB) to the solution.
2.I created this application in Visual studio 2015 it may not run  in Visual studio 2013 and the older versions of VS IDE.
3.Go to server explorer --> expand data base --> Right click Tables --> Add New Table and create table with below schema details and insert some data into table
---Table Schema
CREATE TABLE [dbo].[UserTable] (
    [UserID]     INT          IDENTITY (1, 1) NOT NULL,
    [UserName]   VARCHAR (50) NOT NULL,
    [Address]    VARCHAR (50) NOT NULL,
    [PostalCode] INT          NOT NULL,
    [Phone]      BIGINT       NOT NULL,
    PRIMARY KEY CLUSTERED ([UserID] ASC)
);

---Insert data into Table
SET IDENTITY_INSERT [dbo].[UserTable] ON
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (2, N'Mark', N'Washington', 1092330, 1083438939)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (3, N'Frankinstein', N'New Jersy', 1897337, 1084438434)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (4, N'Gopala krishna', N'Chennai', 5093493, 9348343434)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (5, N'Mishra ', N'Chennai', 5384343, 8384734858)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (6, N'Venugopal', N'Kochin', 5983483, 9893438433)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (7, N'Martin luther', N'London', 4904893, 8384348893)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (8, N'Thomas', N'Kolkata', 5738498, 9934894333)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (9, N'Prasanth Mittal', N'Delhi', 5893483, 9348348333)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (10, N'Sambasiva rao', N'vizag', 5234783, 9948394833)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (11, N'Gopi krishna', N'chennai', 5987343, 9438438344)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (12, N'Venkatesh', N'Hyderabad', 5897349, 8987398473)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (13, N'Ayyar', N'kodykenal', 5989434, 7873843743)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (14, N'Moulali syed', N'Guntur', 5873943, 8908434734)
INSERT INTO [dbo].[UserTable] ([UserID], [UserName], [Address], [PostalCode], [Phone]) VALUES (15, N'Yesdani basha', N'Guntur', 5789343, 9809483403)
SET IDENTITY_INSERT [dbo].[UserTable] OFF
4.Other wise create Table and insert data into DB using above code(Right click Tables --> New Query --> paste code  --> Run using CTRL+ SHIFT +E).

Add ADO.NET Entity Data Model

1.Right click on Models folder--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.
4.Now Model is added to my project.

Add Controller to implement Server side Code

1.Right click Controller --> Add --> Controller --> Select Empty Controller template --> name it(HomeController) --> Add.
2.Add below code to render the web grid in Index View page(adding Index action).
//Data that fills the strongly typed view
        //And displays the View page
        public ActionResult Index()
        {
            List data = new List();
            using (DatabaseEntities db = new DatabaseEntities())
            {
                data = db.UserTables.ToList();
            }
            return View(data);
        }       
3.Now add Index View to Index action Right click Index action --> Add View --> name it.
4.Replace the Index View code with below code..
@model List<ExportWebgridToPdf.Models.UserTable>
@{
    ViewBag.Title = "www.mitechdev.com";
    var grid = new WebGrid(source: Model, canSort: false,rowsPerPage:7);
}
<style>
    .header_style{
        background-color:lightgreen;
    }
</style>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<h3 class="text-info">Delete Multiple Reords once in Webgrid</h3>
<p class="text-info">Select records to Delete</p>
<div>
    @using (Html.BeginForm("DeleteRecords", "Home", FormMethod.Post))
    {
    @grid.GetHtml(
                tableStyle: "table table-responsive table-bordered",
                headerStyle:"header_style",
                columns: grid.Columns(
                    //To display check boxes
                    grid.Column(format:@<text><input type="checkbox" name="UserIDs" value="@item.UserID" /></text>, header: "Select"),
                      grid.Column("UserID", "UserID"),
                      grid.Column("UserName", "User Name"),
                      grid.Column("Address", "Address"),
                      grid.Column("PostalCode", "Postal Code"),
                      grid.Column("Phone", "Phone")
                    )
                )
        <input type="submit" class="btn btn-success" value="Delete Selected" />
    }
</div>

Add action method to Delete Multiple records

1.Replace HomeController.cs code with below Code.

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ExportWebgridToPdf.Models;
namespace ExportWebgridToPdf.Controllers
{
    public class HomeController : Controller
    {
        //Data that fills the strongly typed view
        //And displays the View page
        public ActionResult Index()
        {
            List data = new List();
            using (DatabaseEntities db = new DatabaseEntities())
            {
                data = db.UserTables.ToList();
            }
            return View(data);
        }       
        //Added by Raviteja Swayampu
        //To delete the selected records in Webgrid
        [HttpPost]
        public ActionResult DeleteRecords(string[] UserIDs)
        {
            int[] id = null;
            if (UserIDs != null)
            {
                id = new int[UserIDs.Length];
                int j = 0;
                //assign the values in UserIDs array to int[] array by converting
                foreach(string i in UserIDs)
                {
                    int.TryParse(i, out id[j++]);
                }
            }
            //find and delete those selected records
            if(id!=null & id.Length > 0)
            {
                List selectedList = new List();
                using (DatabaseEntities db = new DatabaseEntities()) {
                    selectedList = db.UserTables.Where(a => id.Contains(a.UserID)).ToList();
                    foreach(var i in selectedList)
                    {
                        db.UserTables.Remove(i);
                    }
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Index");
        }
    }
}
2.Here i am receiving array of IDS from the Index View.Based on IDS i am deleting records from the Web grid.
3.The final outcome of the application is like below.


4.Select some records using checkbox and click on Delete Selected button to delete selected records from web grid.
Download Source code of this application here Source Code(VS2015 code).

Conclusion

I hope this article may helpful for many readers.If you recommend any suggestions i always welcome.Please subscribe to this blog www.mitechdev.com to get posts to your mail inbox.And follow through social networks(Facebook,twitter,google plus) for daily updates...