Grid Paging,Sorting,Searching in ASP.NET MVC

You can easily implement Pagination, Sort and Search functionalities in ASP.NET MVC. In this article I have used PagedList.MVC, Asp.Net MVC HtmlHelper method for generating paging control for use with PagedList library. Along with the Pagination functionality I have also implemented Sort and Search functionalities as well.

Create a New MVC project by selecting the ASP.NET MVC 4 web template from Visual Studio.

Create a Sample Database and Table. If you want to use any other table please continue with that. Below is my sample table structure that I have used in this article.

1

Below are the Code for loading all the Students  from the database. I am using Entityframework for pulling data from the database.

using System.Collections.Generic;
using System.Linq;
using Paging.Mvc.Demo.DAL;
namespace Paging.Mvc.Demo.BL
{
public class StudentInformation
{
public IEnumerable<Student students> GetStudents()
{
var schoolEntities = new SchoolEntities();
return schoolEntities.Students.ToList();
}
}
}

For pagination install a Nuget Package. Go to VisualStudio>Tools>Nuget Package Manager>Package Manager Console and Type command Install-Package PagedList.MVC and press enter. It will add all the references and css for the pagination you need.
2
Create a new controller named StudentController by right clicking on the Controller folder and create a new Action Result named Index and Paste all the codes in the Index method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using PagedList;
using Paging.Mvc.Demo.BL;
using Paging.Mvc.Demo.DAL;

namespace Paging.Mvc.Demo.Controllers
{
public class StudentController : Controller
{
private readonly StudentInformation _studentInformation;
public StudentController()
{
_studentInformation = new StudentInformation();
}
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
//set sort param for sorting name
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";

if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;

IEnumerable<Student students> = _studentInformation.GetStudents().Select(s => s);
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.Name.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.Name);
break;

default:
students = students.OrderBy(s => s.Name);
break;
}
//you can set page index here
const int pageSize = 5;
int pageNumber = (page ?? 1);
return View(students.ToPagedList(pageNumber, pageSize));
}

}
}

Right click the index action and create a new index view. Please make sure that the model type you have returned in the view should be PagedList.IPagedList<Your Entity >

@model PagedList.IPagedList<Paging.Mvc.Demo.DAL.Student>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
ViewBag.Title = "Students";
}
@using (Html.BeginForm("Index", "Student", FormMethod.Get))
{
<p>
Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" />
</p>
}
<table>
<tr>

<th>
@Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter })
</th>

<th>
Place
</th>
<th>
Address
</th>
<th>
Age
</th>
<th>
Father Name
</th>
<th>
Mother Name
</th>
</tr>

@foreach (var item in Model) {
<tr>

<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Place)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.FatherName)
</td>
<td>
@Html.DisplayFor(modelItem => item.MotherName)
</td>

</tr>
}

</table>
<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager( Model, page => Url.Action("Index", new { page, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter }) )

You can download full source code from here

Output
output
Enjoy Coding

OWIN and Katana

  Introduction

Katana is a new webframework that appearing with visual studio 2013. Katana is based on the specification named OWIN. If you started a ASP.NET MVC5  application by using a project template in visual studio you can see some pieces of information related to Katana.
Imagine you are started to develop a new web framework like ASP.NET MVC, How can you interact with the webserver? that is the process is cordinate with OS to listen for Http Request on a socket.How does the software can interact with the host?
We already know ASP.NET is built on the top of Internet Information Services(IIS).The ASP.NET runtime and IIS provide a wonderful collection of features such as Caching,Authentication,Compression,Encryption and some other features like diagnostics which include logging,Request monitoring and others. Not everyone need this features.
In last few years we can see that some architectural changes in the web development.Html5 standards become popular and more processing happens in the client side.Instead of processing heavy operation in the server side for generating html,server is only responsible for handling Ajax request and sending back all data for processing it in the client side.This are the processes happens during mobile application development.

Goal of KATANA

Some people are looking a fast,xtensible framework for developing web application ike Node js. Node is not a webserver itself but easy to add a package or a single library for making a webserver, the webserver exactly has the same features for building a web application nothing more.So the server become and easy to scale.That is the goal of KATANA,provide a light weight piece of software you can use Web applications,websites and web Apis.In ASP.NET MVC everything we needed for web in the system.web assembly, The KATANA is highly modularized we can use whatever the features we want.

Demo

First i am going to create a console application and then process and listen http request using OWIN and KATANA.

1

Step1: Inorder to do that first we need to install some nuget packages.Go to package manager console and install two packages such as Microsoft.Owin.Hosting and Microsoft.Owin.Host.HttpListener.
Package 1 : 
2
Package 2 : 
3

these packages will  add four dependencies in your application

4

 

 

 

 

 

Step2 : Configure KATANA
for configuring this application we need to add a StartUp class contains a method named Configuration which accept a parameter of type IAppBuilder interface. This interface is very important because it includes some methods that allow you to configure how this application is going to behave and respond HttpRequests
5
Step3 : Start the webserver in the entry point of the main method like below and run the application.

6

7

Step 3 : Browse the url we had provide as a URI in the start up

8

Enjoy..coding…

 

Html.Partial,Html.RenderPartial,Html.Action and Html.RenderAction in ASP.NET MVC

Html.Partial and Html.RenderPartial     

  The Html.Partial helpers renders a partial view in to string.You can reuse this Partial Views in Multiple Views. Partial has four overloads
public void Partial(string partialViewName);

public void Partial(string partialViewName, object model);

public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,ViewDataDictionary viewData);
 Example : 
 @Html.Partial("MyPartial")
 
Difference Between Render Partial and Partial

RenderPartial writes directly to the response output stream instead of returning a string. So, you should place RenderPartial inside a code block instead of a code expression

Example :
 @{Html.RenderPartial("MyRenderPartial");}

 So, which should you use, Partial or RenderPartial?

In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream.

Html.Action and Html.RenderAction

         Html.Action and Html.RenderAction are similar to Partial and RenderPartial.Action  executes a separate controller action and display the results.the only difference between Action and RenderAction is that RenderAction writes directly to the response.

 Example :
Imagine you are using the following controller
public class ActionDemoController : Controller {
public ActionResult Index() {
return View();
}

[ChildActionOnly]
public ActionResult DisplayMenu() {
var menu = GetMenuFromSomewhere();
return PartialView(menu);
}
}

The Menu action builds a menu model and returns a partial view with just the menu:
@model Menu
<ul>
@foreach (var item in Model.MenuItem) {
<li>@item.Text</li>
}
</ul>
In your Index.cshtml view, you can now call into the Menu action to display the menu:
<html>
<head><title>Index with Menu</title></head>
<body>
@Html.Action("DisplayMenu")
<h1>Welcome to the Index View</h1>
</body>
</html>

Notice that the Menu action is marked with a ChildActionOnlyAttribute. The attribute prevents the runtime from invoking the action directly via a URL. Instead, only a call to Action or RenderAction can invoke a child action. The ChildActionOnlyAttribute isn’t required, but is generally recommended for child actions.
Passing values to Action
       Sometimes you want to pass parameters in to the action.
Example:
[ChildActionOnly]
public ActionResult Menu(MenuParameters param) {
return PartialView(
param);

}

@Html.Action(“Menu”, new {options = new MenuParameters { Width=400, Height=500 } })

Enjoy Coding…

Load Partial View as Html By using jQuery – Ajax in ASP.NET MVC

Introduction

In ASP.NET MVC we can return a Partial View in the form of PartialViewResult using the PartialView method.
The following example shows Partial update scenarios using Ajax.Using jQuery to load the contents of a PartailView in to the current view using an Ajax call. In this example i have load a simple grid using Ajax.
Controller and Action Result

public class PartialController : Controller
{
public ActionResult GetPartialResult()
{
var list = new List<Album>
{
new Album {Title = "Album1"},
new Album {Title = "Album2"},
new Album {Title = "Album3"},
new Album {Title = "Album4"}
};
return PartialView(list);
}

}

public class Album
{
public string Title { get; set; }
}

Right click the ActionResult and Create a PartialView like below
@model IEnumerable<Mvc4Demos.Controllers.Album>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
</tr>
}
</table>

Here when a button click load the PartialViewResult by using Ajax and Append in to a Result div
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#result').load('/Partial/GetPartialResult');
});
});

</script>
<input type="button" id="btn" value="PartialExample"/>
<div id="result"></div>

Enjoy Reading…