Thursday, November 20, 2014

MV AJAX Sorting Implementation

1) Create a SortedData class


        public class SortedData where T : class
        {
            public IEnumerable Data { get; set; }
            public string SortOrder { get; set; }
        }

2) Define the Index action in the controller as shown below.


  public ViewResult Index()
        {
            try
            {
                SortedData<Album> sortedData = new SortedData<FeedBack>();
                sortedData.SortOrder = "desc";
                sortedData.Data = GetData();
                return View(sortedData);
            }
            catch (ApplicationException aex)
            {
                return View(new List<FeedBack>());
            }
        }

3) Define the SortedList action in the controller as shown below.



public ActionResult SortedList(string sortOrder)
        {
            try
            {
                var albums = GetData();
                SortedData<Album> sortedData = new SortedData<FeedBack>();
                if(sortOrder == "desc")
                {
                    sortedData.SortOrder = "asc";
                    sortedData.Data = albums.OrderByDescending(a => a.Name).ToList();
                }
                else
                {
                    sortedData.SortOrder = "desc";
                    sortedData.Data = albums.OrderBy(a => a.Name).ToList();
                }
                return PartialView(sortedData);
            }
            catch (ApplicationException aex)
            {
                return PartialView(new List<FeedBack>());
            }

        }

4) Define Index.cshtml view as shown below

@model MvcMusicStore.Controllers.StoreManagerController.SortedData<MusicStore.Data.Models.FeedBack>
@{
    ViewBag.Title = "Index";
}
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">
    $().ready(
    function () {
        $(".artist-sort").live("click", function () {
            var sortOrder = "desc"
            sortOrder = $(".sOrder").text()
            $.ajax(
            {
                url: '@Url.Action("SortedList")',
                data: { "sortOrder": sortOrder },
                success: function (data) {
                    $("#sorted-list").html(data);
                }
            });
        });
    });
</script>
<h2>Index</h2>
<div id="sorted-list">
   @Html.Partial("SortedList")
</div>

5) Define SortedList view as shown below.

@model MvcMusicStore.Controllers.StoreManagerController.SortedData<MusicStore.Data.Models.FeedBack>

@helper Truncate(string input, int length)
{
    if (input.Length <= length) {
        @input
    } else {
        @input.Substring(0, length)...
    }
}
@{
    ViewBag.Title = "Index";
}
<p>
    @Html.ActionLink("Create New", "Create")
</p>
test <span class="sOrder">@Model.SortOrder</span>
<table>
    <tr>
        <th>
            Genre
        </th>
        <th>
        <a class="artist-sort" href="javascript:void();">Artist</a>
        </th>
        <th>
            Title
        </th>
        <th>
            Price
        </th>
        <th></th>
    </tr>
@foreach (var item in Model.Data) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name) 
        </td>
        <td>
            @MvcMusicStore.Code.Helpers.Truncate(item.Name, 25)
        </td>
        <td>
            @MvcMusicStore.Code.Helpers.Truncate(item.Title, 25)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.FeedBackId }) |
            @Html.ActionLink("Details", "Details", new { id=item. FeedBackId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item. FeedBackId })
        </td>
    </tr>
}
</table>

 










Tuesday, November 11, 2014

MVC Ajax Paging Implementation

Steps to implement paging using Ajax in MVC application


1) Create a PagedData class


public class PagedData where T : class
{   public IEnumerable Data { get; set; }
   public int CurrentPage { get; set; }
   public int NumberOfPages { get; set; }
}
 

2) Define the Index action in the controller as shown below.


public const int PageSize = 4;
        //

        // POST: /FeedBack/Index

        public ActionResult Index()
        {
            try
            {
                var feedBacks = ServiceWebClient.GetAllFeedBacks();
                var feedBacksList = new PagedData<FeedBack>();
                feedBacksList.Data = feedBacks.OrderBy(f => f.FeedBackId)
                                             .Take(PageSize).ToList();
                feedBacksList.NumberOfPages = Convert.ToInt32(Math.Ceiling((double)feedBacks.Count() / PageSize));

               return View(feedBacksList);
           }
            catch (ApplicationException aex)
            {
                ViewBag.MasterErrorMessage = aex.Message;
                return View("Error");
            }
        }

3) Define the PagedList action in the controller as shown below.



        // POST: /FeedBack/PagedList

        public ActionResult PagedList(int page)
        {
            try
            {
                var feedBacks = ServiceWebClient.GetAllFeedBacks();
                var feedBacksList = new PagedData<FeedBack>();
                feedBacksList.Data = feedBacks.OrderBy(f => f.FeedBackId)
                                              .Skip(PageSize * (page - 1))
                                              .Take(PageSize).ToList();
                feedBacksList.NumberOfPages = Convert.ToInt32(Math.Ceiling((double)feedBacks.Count() / PageSize));
                feedBacksList.CurrentPage = page;
                return PartialView(feedBacksList);
            }
            catch (ApplicationException aex)
            {
               ViewBag.MasterErrorMessage = aex.Message;
                return View("Error");
            }
        }
       

4) Define Index.cshtml view as shown below


@model MvcMusicStore.Controllers.FeedBackController.PagedData<MusicStore.Data.Models.FeedBack>
@{
    ViewBag.Title = "All FeedBacks";
}
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script type="text/javascript">

   var currentPage = 1;
   $().ready(
    function () {
        $(".page-number").live("click", function () {
            var page = parseInt($(this).html());
            currentPage = page;
            $.ajax(
            {
                url: '@Url.Action("PagedList")',
                data: { "page": page },
                success: function (data) {
                    $("#feedback-list").html(data);
                }
            });
        });
</script>

<h2>Feedbacks</h2>
<div id="feedback-list">
    @Html.Partial("PagedList")
</div>
 

4) Define PagedList view as shown below.

@model MvcMusicStore.Controllers.FeedBackController.PagedData<MusicStore.Data.Models.FeedBack>
@{
    ViewBag.Title = "All FeedBacks";
}
<h2>Details</h2>
<table>
   <tr>
       <th>
       <a class="name-sort" href="javascript:void();">Name</a>
        </th>
        <th>
            Comment
        </th>
        <th></th>
    </tr>
@foreach (var item in Model.Data) {
    <tr>
        <td>
            @Html.DisplayFor(feed => item.Name)
        </td>
        <td>
            @Html.DisplayFor(feed => item.Comment)
        </td>
        <td>
            @Html.ActionLink("Details", "Details", new { id = item.FeedBackId }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.FeedBackId })
        </td>
    </tr>

}
<tfoot>
        <tr>
            <td colspan="3">
                @for (int i = 1; i <= Model.NumberOfPages; i++)
                {
                    <a class="page-number" href="javascript:void();">@i</a>
                }
            </td>
        </tr>
    </tfoot>
</table>

@if (Model.NumberOfPages > 0)
{
    <div>Page @(Model.CurrentPage == 0 ? 1 : Model.CurrentPage) of @Model.NumberOfPages</div>
}

 Few more improvements

Add the following code in Index view.
        $(".prevButton").live("click", function () {
            var page = parseInt($(this).attr('pageNo'));
            currentPage = page;
            $.ajax(
            {
                url: '@Url.Action("PagedList")',
                data: { "page": page },
                success: function (data) {
                    $("#feedback-list").html(data);
                }
            });
        });

        $(".nextButton").live("click", function () {
            var page = parseInt($(this).attr('pageNo'));
            currentPage = page;
            $.ajax(
            {
                url: '@Url.Action("PagedList")',
                data: { "page": page },
                success: function (data) {
                    $("#feedback-list").html(data);
                }
            });
        });


Add the following code in paged list view

<tfoot>
        <tr>
            <td colspan="3">
                @for (int i = 1; i <= Model.NumberOfPages; i++)
                {
                    if (ViewBag.CurrentPage == i)
                    {
                        <a class="page-number" href="javascript:void();" style="font-size:large;color:Green">@i</a>
                    }
                    else
                    {
                        <a class="page-number" href="javascript:void();" style="font-size:small">@i</a>
                    }
                }
            </td>
        </tr>
    </tfoot>
</table>

 

@if (Model.NumberOfPages > 0)
{
    <table style="width:25;border:1px; margin:0px 0px 0px 0px; padding:0px 0px 0px 0px">
    <tr>
    <td>
        @if (Model.CurrentPage > 1)
        {
            <p id="divPreviousButton" class="button">
                <a class="prevButton" href="javascript:void();" pageNo=@(Model.CurrentPage == 0 ? 1 : Model.CurrentPage - 1)><<Previous</a>
            </p>
        }
    </td>
    <td>
        <div>Page @ViewBag.CurrentPage of @Model.NumberOfPages</div>
    </td>
    <td>
        @if (Model.CurrentPage < Model.NumberOfPages)
        {
            <p id="divNextButton" class="button">
                <a class="nextButton" href="javascript:void();" pageNo=@(Model.CurrentPage == 0 ? 2 : Model.CurrentPage + 1)>Next>></a>
           </p>
        }
    </td>
    </tr>
    </table>
}