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

Leave a Comment
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...

Wednesday, 27 July 2016

CRUD operations on Angular UI Calendar(Event Scheduling)

Leave a Comment
Hi every one thank for recommendations for the previous post Implementing Event Scheduling in Angular UI Calendar.In this tutorial  i am going to explain about how to implement CRUD operations on UI calendar.If you are new to this post please refer above link Implementing Event Scheduling in Angular UI to understand the implementation of basic UI calendar and how to load events data from server to display on calendar.
In this tutorial i am going to use the previous post code.The below screen shot represents the previous application.
CRUD operations on Angular UI Calendar(Event Scheduling)

CRUD operations on Angular UI Calendar(Event Scheduling)

1.Create a Visual studio application (in this application is created in VS2015).
2.See previous article to know the Calendar implementation click here .
3.You can find what libraries to Add and How to get and display server data in UI-calendar from previous post.
4. I am using same table schema and ADO.NET Data Model from the previous post.

Add Controller to display view and CRUD functions

1.Right click on Controllers folder --> Add --> Select Empty Controller template --> name it (HomController) --> Add.
2.Replace the previous code with below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AngularUICalendarCRUd.Models;

namespace AngularUICalendarCRUd.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetEvents()
        {
            //Here MyDatabaseEntities is our entity datacontext (see Step 4)
            using (DatabaseEntities dc = new DatabaseEntities())
            {
                var v = dc.Events.OrderBy(a => a.StartAt).ToList();
                return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }
        //Action for Save event
        [HttpPost]
        public JsonResult SaveEvent(Event evt)
        {
            bool status = false;
            using (DatabaseEntities dc = new DatabaseEntities())
            {
                if (evt.EndAt != null && evt.StartAt.TimeOfDay == new TimeSpan(0, 0, 0) &&
                    evt.EndAt.TimeOfDay == new TimeSpan(0, 0, 0))
                {
                    evt.IsFullDay = true;
                }
                else
                {
                    evt.IsFullDay = false;
                }

                if (evt.EventID > 0)
                {
                    var v = dc.Events.Where(a => a.EventID.Equals(evt.EventID)).FirstOrDefault();
                    if (v != null)
                    {
                        v.Title = evt.Title;
                        v.Description = evt.Description;
                        v.StartAt = evt.StartAt;
                        v.EndAt = evt.EndAt;
                        v.IsFullDay = evt.IsFullDay;
                    }
                }
                else
                {
                    dc.Events.Add(evt);
                }
                dc.SaveChanges();
                status = true;
            }
            return new JsonResult { Data = new { status = status } };
        }
        [HttpPost]
        public JsonResult DeleteEvent(int eventID)
        {
            bool status = false;
            using (DatabaseEntities dc = new DatabaseEntities())
            {
                var v = dc.Events.Where(a => a.EventID.Equals(eventID)).FirstOrDefault();
                if (v != null)
                {
                    dc.Events.Remove(v);
                    dc.SaveChanges();
                    status = true;
                }
            }
            return new JsonResult { Data = new { status = status } };
        }
    }
}
3.SaveEvent saves the event data to data basae.DeleteEvent deletes the event data from data base.
4.Index action to render the Index view.
5.Make below changes to _Layout.cshtml page in Shared folder.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body> 
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
</body>
</html>

Add View to display the UI

1.Right click on Index action in HomeController.cs file --> Add --> name it (Index) --> Add.
2.Replace the Index.cshtml page code with below code.
@{
    ViewBag.Title = "Index";
}
<h2>Angular UI calender Events Scheduling CRUD operations</h2>
<!--Styles for UI calender-->
<link href="~/Content/fullcalendar.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<!--Angualar script libraries-->
<script src="~/Scripts/moment.js"></script>
<script src="~/Scripts/jquery-1.11.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<script src="~/Scripts/calendar.js"></script>
<script src="~/Scripts/fullcalendar.js"></script>
<script src="~/Scripts/gcal.js"></script>
<!--Current application Scripts-->
<script src="~/Scripts/myscript.js"></script>
<!--Bootstrap Angular UI Modal popup script library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.2/ui-bootstrap-tpls.min.js"></script>
@* HTML *@
<div ng-app="myapp" ng-controller="CalenderController">
     <!--Angular template for modal dialog code structure starts here-->
    <script type="text/ng-template" id="modalContent.html">
        <div class="modal-header">
            <h3 class="modal-title">Events</h3>
        </div>
        <div class="modal-body">
            <div style="color:red">{{Message}}</div>
            <div class="form-group">
                <label>Event Title : </label>
                <input type="text" ng-model="NewEvent.Title" autofocus class="form-control" />
            </div>
            <div class="form-group">
                <label>Description : </label>
                <input type="text" ng-model="NewEvent.Description" class="form-control" />
            </div>
            <div class="form-group">
                <label>Time Slot : </label>
                <span>{{NewEvent.StartAt}} - {{NewEvent.EndAt}}</span>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" type="button" ng-click="ok()">Save</button>
            <button class="btn btn-danger" type="button" ng-show="NewEvent.EventID > 0" ng-click="delete()">Delete</button>
            <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>

        </div>
        <!--Angular modal dialog code ends here-->
    </script>
    <div class="row">
        <div class="col-md-12">
            <!--this element displays the UI-caledar-->
            <div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
        </div>      
    </div>
</div>
3.I am using Bootstrap Angular UI Modal popup to Create,Edit and Delete the Events created in the UI calendar.

Add Script for Calendar Functionality

1.Right click on Scripts folder --> Add --> Java script file.
2.Add below script code for UI -calendar display and CRUD operations.


//ui.calendar --> for caledar control
//ui.bootstrap  --> for bootstrap angualr UI modal popup
var app = angular.module('myapp', ['ui.calendar', 'ui.bootstrap']);
app.controller('CalenderController', ['$scope', '$http', 'uiCalendarConfig', '$uibModal', function ($scope, $http, uiCalendarConfig, $uibModal) {    
    $scope.SelectedEvent = null;
    var isFirstTime = true;
    $scope.events = [];
    $scope.eventSources = [$scope.events];

    $scope.NewEvent = {};
    //this function for get datetime from json date
    function getDate(datetime) {
        if (datetime != null) {
            var mili = datetime.replace(/\/Date\((-?\d+)\)\//, '$1');
            return new Date(parseInt(mili));
        }
        else {
            return "";
        }
    }
    // this function clears clender enents
    function clearCalendar() {
        if (uiCalendarConfig.calendars.myCalendar != null) {
            uiCalendarConfig.calendars.myCalendar.fullCalendar('removeEvents');
            uiCalendarConfig.calendars.myCalendar.fullCalendar('unselect');
        }
    }
    //Load events from server to display on caledar
    function populate() {
        clearCalendar();
        $http.get('/home/getevents', {
            cache: false,
            params: {}
        }).then(function (data) {
            $scope.events.slice(0, $scope.events.length);
            angular.forEach(data.data, function (value) {
                $scope.events.push({
                    id : value.EventID,
                    title: value.Title,
                    description: value.Description,
                    start: new Date(parseInt(value.StartAt.substr(6))),
                    end: new Date(parseInt(value.EndAt.substr(6))),
                    allDay: value.IsFullDay,
                    stick: true
                });
            });
        });
    }
    populate();
    //UI- calendar configuration
    $scope.uiConfig = {
        calendar: {
            height: 450,
            editable: true,
            displayEventTime: true,
            header: {
                left: 'month,agendaWeek,agendaDay',
                center: 'title',
                right:'today prev,next'
            },
            timeFormat : {
                month : ' ', // for hide on month view
                agenda: 'h:mm t'
            },
            selectable: true,
            selectHelper: true,
            select : function(start, end){
                var fromDate = moment(start).format('YYYY/MM/DD LT');
                var endDate = moment(end).format('YYYY/MM/DD LT');
                $scope.NewEvent = {
                    EventID : 0,
                    StartAt : fromDate,
                    EndAt : endDate,
                    IsFullDay :false,
                    Title : '',
                    Description : ''
                }

                $scope.ShowModal();
            },
            eventClick: function (event) {
                $scope.SelectedEvent = event;
                var fromDate = moment(event.start).format('YYYY/MM/DD LT');
                var endDate = moment(event.end).format('YYYY/MM/DD LT');
                $scope.NewEvent = {
                    EventID : event.id,
                    StartAt : fromDate,
                    EndAt : endDate,
                    IsFullDay :false,
                    Title : event.title,
                    Description : event.description
                }

                $scope.ShowModal();
            },
            eventAfterAllRender: function () {
                if ($scope.events.length > 0 && isFirstTime) {
                    uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
                    isFirstTime = false;
                }
            }
        }
    };

    //This function shows bootstrap modal dialog
    $scope.ShowModal = function () {
        $scope.option = {
            templateUrl: 'modalContent.html',
            controller: 'modalController',
            backdrop: 'static',
            resolve: {
                NewEvent: function () {
                    return $scope.NewEvent;
                }
            }
        };
        //CRUD operations on Calendar starts here
        var modal = $uibModal.open($scope.option);
        modal.result.then(function (data) {
            $scope.NewEvent = data.event;
            switch (data.operation) {
                case 'Save':            //save
                    $http({
                        method: 'POST',
                        url: '/home/SaveEvent',
                        data : $scope.NewEvent
                    }).then(function (response) {
                        if (response.data.status) {
                            populate();
                        }
                    })
                    break;
                case 'Delete':          //delete
                    $http({
                        method: 'POST',
                        url: '/home/DeleteEvent',
                        data: {'eventID' : $scope.NewEvent.EventID }
                    }).then(function (response) {
                        if (response.data.status) {
                            populate();
                        }
                    })
                    break;
                default:
                    break;
            }
        }, function () {
            console.log('Modal dialog closed');
        })
    }
}])
3.In above code i used $http service to contact with server(for save,Edit and delete oeprations).
4.Add below code to display the Bootstrap Angular UI Modal popup.
// create a new controller for Bootstrap Angualr modal popup
app.controller('modalController', ['$scope', '$uibModalInstance', 'NewEvent', function ($scope, $uibModalInstance,NewEvent) {
    $scope.NewEvent = NewEvent;
    $scope.Message = "";
    $scope.ok = function () {
        if ($scope.NewEvent.Title.trim() != "") {
            $uibModalInstance.close({event : $scope.NewEvent, operation: 'Save'});
        }
        else {
            $scope.Message = "Event title required!";
        }
    }
    $scope.delete = function () {
        $uibModalInstance.close({ event: $scope.NewEvent, operation: 'Delete' });
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    }
}])
5.Finally run the application and see the output in browser.

CRUD operations on Angular UI Calendar(Event Scheduling)

6.To create new event click on any Date.then you get a popup like below.

CRUD operations on Angular UI Calendar(Event Scheduling)

 7.To perform EDIT and DELETE operations click on any event.

CRUD operations on Angular UI Calendar(Event Scheduling)

Download the source code for 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...