AJAX paging for ASP.NET MVC sites

When working with lists of data paging is a necessity, but trivial to implement in an ASP.NET MVC. The article Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application on www.asp.net makes use of the PackedList.MVC NuGet package and each step is described in detail. The implementation requires full-page refresh and does not make use of AJAX capabilities.

Let us extend the implementation and make full use of the AJAX capabilities.

Wrap the entire table in a div-tag and give it an id of content – it will enable us to replace the table without refreshing the entire webpage.

<div id="content">
    <table>
        ... removed for brevity
    </table>

    <div id="contentPager">
        @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
    </div>
</div>

Also wrap the @Html.PagedListPager in a div-tag and set the id to contentPager – it will let us alter the behavior of the click-event.

The below JQuery code attaches the anonymous function to every a-tag within the contentPager element and the function replaces the html within the content element with whatever is returned from the AJAX call.

$(document).on("click", "#contentPager a", function () {
    $.ajax({
        url: $(this).attr("href"),
        type: 'GET',
        cache: false,
        success: function (result) {
            $('#content').html(result);
        }
    });
    return false;
});

Move everything within the content element to a new view – let us call the new view List.

@model PagedList.IPagedList<ContosoUniversity.Models.Student>
@using PagedList.Mvc;

<div id="content">
    <table class="table">
      ... removed for brevity
    </table>

    <div id="contentPager">
        @Html.PagedListPager(Model, page => Url.Action("List", new { page }))
    </div>
</div>

Notice in above highlighted code, that the Action URL is changed to List, which is the name of the Action we need to add to the StudentController.

public ActionResult List(int? page)
{
    var students = from s in db.Students
                    orderby s.LastName
                    select s;

    int pageSize = 3;
    int pageNumber = (page ?? 1);
    return View(students.ToPagedList(pageNumber, pageSize));
}

The functionality of the new List Action is the same as in the existing Index Action. Just move all the code from the Index Action, so it just returns the default view as below.

public ViewResult Index()
{
    return View();
}

To wrap it up, the Index view needs to call the List Action to render the table in the Index view.

So the Index view ends up looking like this.

<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
    ViewBag.Title = "Students";
}
<h2>Students</h2>

@Html.Action("List")

@section scripts
{
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $(document).on("click", "#contentPager a[href]", function () {
                $.ajax({
                    url: $(this).attr("href"),
                    type: 'GET',
                    cache: false,
                    success: function (result) {
                        $('#content').html(result);
                    }
                });
                return false;
            });
        });
    </script>
}

That is it.

The solution is inspired by this StackOverflow question.

Download the complete solution, build and open the Student page.

Clean Domain Model via MongoDB Class Map

You can get rid of the dependency from the domain model to MongoDB assemblies, by utilizing Class Map functionality of the Official MongoDB C# Driver.

It is simple to use the property mapping, but you can also use AutoMap combined with one or more overriding mappings. That is often useful when using the MongoDB IdGenerators. However, how do you specify which to use without using attributes?

Below is a simple class with no dependencies – only dependent on the .NET Base Class Library:

public class Person
{
  public string Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Notice that not event an ObjecId is present.
To instruct MongoDB to generate a unique identifier for the Id property:

public class Person
{
  [BsonId]
  public string Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

But now there is a dependency on the BSonId attribute. We can remove it via a Class Map:

BsonClassMap.RegisterClassMap(cm =>
            {
                cm.AutoMap();
                cm.SetIdMember(cm.GetMemberMap(x => x.Id)
                  .SetIdGenerator(StringObjectIdGenerator.Instance));
            });

It is possible to use other data types as unique identifiers; just choose the correspond IdGenerator.

MongoDB auto-increment or sequence

MongoDB is a document database that does not have auto-increment or sequence functionality build-in, like e.g. SQL Server. Auto-increment or sequence numbers are often used to create a consecutive sequence of numbers used as order or invoice identifiers.

This is simple to achieve with MongoDB via the atomic operation $inc. If you use the Official MongoDB C# Driver the operation is exposed via the Update class.

To implement auto-increment or sequence functionality with MongoDB a document is required to keep the state of the sequence. The Id is the natural name of the sequence e.g. orderid and the value is the current counter value.

class Counter
{
  public string Id { get; set; }
  public int Value { get; set; }
}

Then getting the next ordered is done by executing the below statement:

var client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("myDatabase");
var counterCol = db.GetCollection("counters")

var result = counterCol.FindAndModify(new FindAndModifyArgs()
{
  Query = Query.EQ(d => d.Id, "orderId"),
  Update = Update.Inc(d => d.Value, 1),
  VersionReturned = FindAndModifyDocumentVersion.Modified,
  Upsert = true, //Create if the document does not exists
});

I am a Softie

Microsoft logo

Softie is internal slang for Microsoft employee.

For a couple of years I have had my own company Avior together with my partner. We had fun times and difficult times, but we did what we loved – developed software. Late September I started talking with Microsoft Denmark about the position as technical evangelist. At first I was reluctant as I was afraid to lose my technical competence and leaving my own company, but I was intrigued. I finally agreed to leave Avior and join Microsoft after a couple of conversations with current and previously Microsoft employees – they all spoke fondly about Microsoft – if I could cope with the politics and ceremony.

What is the job of a technical evangelist?

An evangelist advocates the evangelium, which means ‘good news’. All Latin, nothing religious – but in my case just technical :)

It is about connecting people who have problems with a product, technology and knowledge needed in order for them to succeed. In my mind, it is all about authentic content, communication, and community. I wish to spread knowledge and help other developers while keeping my integrity.

Current status

Now 3 months in, I find myself at home at Microsoft, but I still feel like a n00b. There are so many people and internal processes that I need to familiarize myself with that I sometimes feel dizzy and do not feel that I am contributing enough.

Challenges

I am catching up on the Windows 8, Windows Phone 8 and Azure – which is the new stuff at Microsoft. It is a lot of ground to cover, so I do no longer fear for my technical competencies as I am spending much time studying and helping customers with technical issues.

I wish to engage the community more in the New Year, so I am busy planning talks and the Danish Developer Conference.

One request for you – let me know how I am doing, please.

Merry Christmas and happy New Year.