-2

I want to make pagination with 5 articles per page using asp.net MVC, what code should I add?

Here my controller:

    using CBA.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CBA.ViewModels;
using System.Data;

namespace CBA.Controllers
{
    public class EventController : Controller
    {
        private ModelEntities db = new ModelEntities();

       public ActionResult Index()
        //public ActionResult Index(int page = 1, int pageSize 5)
        {
            EventDetailsViewModel eventDetail = new EventDetailsViewModel();
            MasterEvents events = new MasterEvents();

            eventDetail.Title = events.Title;
            eventDetail.CreatedTime = events.CreatedTime;
            eventDetail.Detail = events.DetailEvent;
            eventDetail.CreatedBy = events.CreatedBy_Id;
            eventDetail.Description = events.ShortDescription;

            CBA.GetContent.GetContentSoapClient service = new CBA.GetContent.GetContentSoapClient();

            string[] Content = service.GetContentText("Events", DateTime.Now.ToString("MM-dd-yyyy"), clsEncrypt.EncodeTo64(DateTime.Now.ToString("MM-dd-yyyy")));
            if (Content[0] != null)
            {
                string id = Content[0];

                string ContentText;

                if (Content[1].Length == 0 && Content[2].Length == 0 && Content[3].Length == 0)
                {
                    ContentText = "";
                }
                else
                {
                    ContentText = "<div class=\"container\" #MARGIN-TOP# ><div class=\"row\"><div class=\"col-lg-10 col-lg-offset-1\">";
                    ContentText += "<div class=\"col-lg-12\" style=\"text-align:center;\"><h1>" + Content[1] + "</h1></div>";
                    ContentText += "<div class=\"col-lg-12\" style=\"text-align:center;\"><h2>" + Content[2] + "</h2></div>";
                    ContentText += "<div class=\"col-lg-12\"><div class=\"form-group\">" + HttpUtility.HtmlDecode(Content[3]).Replace("src=\"/", "src=\"" + System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"] + "/") + "</div>";
                    ContentText += "</div></div></div>";
                }

                DataTable dtSlider = service.GetContentImageSlider(int.Parse(id), DateTime.Now.ToString("MM-dd-yyyy"), clsEncrypt.EncodeTo64(DateTime.Now.ToString("MM-dd-yyyy")));

                if (dtSlider.Rows.Count > 0)
                {

                    string ContentSlider = "<div id=\"myCarousel\" class=\"carousel slide\"><ol class=\"carousel-indicators\">";

                    for (int i = 0; i < dtSlider.Rows.Count; i++)
                    {
                        if (i == 0)
                        {
                            ContentSlider += "<li data-target=\"#myCarousel\" data-slide-to=\"" + i.ToString() + "\" class=\"active\"></li>";
                        }
                        else
                        {
                            ContentSlider += "<li data-target=\"#myCarousel\" data-slide-to=\"" + i.ToString() + "\"></li>";
                        }
                    }

                    ContentSlider += "</ol><div class=\"carousel-inner\">";

                    for (int i = 0; i < dtSlider.Rows.Count; i++)
                    {
                        //dt.Columns.Add("ImageFile", typeof(string));
                        //dt.Columns.Add("HeaderText", typeof(string));
                        //dt.Columns.Add("ContentText", typeof(string));

                        string img = dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]);

                        if (i == 0)
                        {
                            ContentSlider +=
                                "<div class=\"item active\" style=\"background:url('" + dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]) + "') "
                                + "no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; "
                                + "-o-background-size: cover;background-size: cover;\">"
                                    + "<div class=\"container\">"
                                        + "<div class=\"carousel-caption\">"
                                            + "<div class=\"col-lg-6\" style='width:260px;'>"
                                                + "<h1>" + (string)dtSlider.Rows[i]["HeaderText"] + "</h1>"
                                                + "<p class=\"scroll_bni\" style='width: 260px;'>"
                                                    + (string)dtSlider.Rows[i]["ContentText"]
                                                + "</p>"
                                            + "</div>"
                                        + "</div>"
                                    + "</div>"
                                + "</div>";
                        }
                        else
                        {
                            ContentSlider +=
                                   "<div class=\"item\" style=\"background:url('" + dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]) + "') "
                                   + "no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; "
                                   + "-o-background-size: cover;background-size: cover;\">"
                                       + "<div class=\"container\">"
                                           + "<div class=\"carousel-caption\">"
                                               + "<div class=\"col-lg-6\" style='width:260px;'>"
                                                   + "<h1>" + (string)dtSlider.Rows[i]["HeaderText"] + "</h1>"
                                                   + "<p class=\"scroll_bni\" style='width: 260px;'>"
                                                       + (string)dtSlider.Rows[i]["ContentText"]
                                                   + "</p>"
                                               + "</div>"
                                           + "</div>"
                                       + "</div>"
                                   + "</div>";
                        }
                    }

                    ContentSlider += "</div><a class=\"left carousel-control\" href=\"#myCarousel\" data-slide=\"prev\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a><a class=\"right carousel-control\" href=\"#myCarousel\" data-slide=\"next\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a></div>";

                    ViewBag.Carousel = ContentSlider;
                }
                else
                {
                    ContentText = ContentText.Replace("#MARGIN-TOP#", "style=\"margin-top:60px;\"");
                }

                ContentText = ContentText.Replace("#MARGIN-TOP#", "");

                ViewBag.Content = ContentText;
            }

            return View(db.MasterEvents.ToList());
        }


        public ActionResult ViewEvents(int id)
        {
            MasterEvents MasterEvents = db.MasterEvents.Find(id);
            ViewBag.data = id;
            return View();
        }
}
}

Here my view:

 @model IEnumerable<CBA.Models.MasterEvents>

@{
    ViewBag.Title = "Recruitment - DDR Events";
    ViewBag.lnkEvents = "active";
    Layout = "~/Views/Shared/ContentFrontEnd.cshtml";
}

<!-- Carousel
    ================================================== -->
@Html.Raw(ViewBag.Carousel)
<!-- /.carousel -->
<!-- Content
    ================================================== -->
@Html.Raw(ViewBag.Content)
<!-- /.Content -->


<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div class="container" style="background-color: white; border-radius: 0 0 15px 15px; margin-bottom: 40px;">
        <div class="row" style="margin-top: 30px;">
            <div class="col-lg-10 col-lg-offset-1">
                @foreach (var item in Model)
                {
                    <div class="blog-post">
                        <h2 class="blog-post-title">@Html.DisplayFor(modelItem => item.Title)</h2>
                        <p class="blog-post-meta">
                            Created Time @Html.DisplayFor(modelItem => item.CreatedTime)
                            <!--by <a href="#">@Html.DisplayFor(modelItem => item.CreatedBy_Id)</a></p>-->
                            <h2 class="blog-post-title">@Html.DisplayFor(modelItem => item.ShortDescription)</h2>
                            <div class="readmore">
                          <p>
@{
                            string parameterValue = "";
                            if (item.DetailEvent.ToString().Length < 100)
                            {
                               parameterValue = item.DetailEvent; 
                            }
                            else
                            {
                                parameterValue = item.DetailEvent.ToString().Substring(0, 200); 


                            }
                            }
 @Html.Raw(parameterValue);
                                </p>
                            </div>
                            <br />
 @Html.ActionLink("Read More..", "ViewEvents", "Event", new { id = 7 }, new { @class = "btn btn-primary btn-lg", style = "width:180px;" })

                        </p>
                         <p class="blog-post-meta">
                            Update Time @Html.DisplayFor(modelItem => item.UpdatedTime)
                        <p>
                        </div> 
                }
                <nav>
                    <ul class="pager">
                        <li><a href="#">Previous</a></li>
                        <li><a href="#">Next</a></li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</body>
</html>

Here my models:

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Web;

    namespace CBA.Models
    {
        public class MasterEvents
        {
            [Key]
            [DisplayName("ID")]
            [ScaffoldColumn(false)]
            public int Id { get; set; }

            [Required(ErrorMessage = "Required Events Title")]
            [DisplayName("Title")]
            [StringLength(250)]
            public string Title { get; set; }

            [Required(ErrorMessage = "Required Short Description")]
            [DisplayName("Short Description")]
            [StringLength(250)]
            public string ShortDescription { get; set; }

            [Required(ErrorMessage = "Required Details")]
            [DisplayName("Detail Events")]
            [StringLength(20)]
            public string DetailEvent { get; set; }

            [DisplayName("Created Time")]
            public System.DateTime? CreatedTime { get; set; }

            [DisplayName("Updated Time")]
            public System.DateTime? UpdatedTime { get; set; }

            [DisplayName("Created By")]
            public int? CreatedBy_Id { get; set; }

            [DisplayName("Updated By")]
            public int? UpdatedBy_Id { get; set; }


        }
    }

How to make pagination, I want to make pagination with 5 articles per page..

  • 1
    So you're asking us to write the code for you? That's not how Stack Overflow works. What have *you* tried? Have you thought about what you'll need to pass to the controller to indicate what page your on, or how you'll query the correct number of items from the database? Have you looked elsewhere online to see how pagination is implemented? – mason Apr 20 '16 at 02:16
  • That's a pretty complicated index controller method you have there. – Mark Schultheiss Apr 20 '16 at 03:53
  • All that HTML you are building in the controller needs to move to the view. You can make the if-then and foreaches there. – Core-One Apr 20 '16 at 05:08

1 Answers1

0

Pagination in any system generally involves taking a page number and a count per page in the controller method so that you can then pass these values to your search method in the business layer or data access layer to get only the content that you need.

So essentially:

Modify the Index controller method to something like this: Index(int page = 1, int countPerPage = 5)

This will allow you to pass the page number and count per page in the controller which you can then use to pass to the search method.

You will also need to create a UI which shows the page numbers. One way to calculate how many pages you will need to show is by returning the TOTAL number of items present in the search (from your search method) and then dividing this by the countPerPage value.

I hope this pushes you in the right direction.

Here are some resources for further reading:

How do I do pagination in ASP.NET MVC?

and

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

which should give you a better idea.

Community
  • 1
  • 1
saurabhj
  • 2,357
  • 2
  • 24
  • 34