Wednesday, May 22, 2013

Understanding Action Filters in Asp.Net MVC

The goal of this tutorial is to explain action filters. An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:

  • OutputCache – This action filter caches the output of a controller action for a specified amount of time.
  • HandleError – This action filter handles errors raised when a controller action executes.
  • Authorize – This action filter enables you to restrict access to a particular user or role.
You also can create your own custom action filters. For example, you might want to create a custom action filter in order to implement a custom authentication system. Or, you might want to create an action filter that modifies the view data returned by a controller action.
In this tutorial, you learn how to build an action filter from the ground up. We create a Log action filter that logs different stages of the processing of an action to the Visual Studio Output window.

Using an Action Filter

An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
For example, the Data controller in Listing 1 exposes an action named Index() that returns the current time. This action is decorated with the OutputCache action filter. This filter causes the value returned by the action to be cached for 10 seconds.
Listing 1 – Controllers\DataController.cs
using System;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
     public class DataController : Controller
     {
          [OutputCache(Duration=10)]
          public string Index()
          {
               return DateTime.Now.ToString("T");

          }
     }
}
        
If you repeatedly invoke the Index() action by entering the URL /Data/Index into the address bar of your browser and hitting the Refresh button multiple times, then you will see the same time for 10 seconds. The output of the Index() action is cached for 10 seconds (see Figure 1).
Figure 01: Cached time (Click to view full-size image)
In Listing 1, a single action filter – the OutputCache action filter – is applied to the Index() method. If you need, you can apply multiple action filters to the same action. For example, you might want to apply both the OutputCache and HandleError action filters to the same action.
In Listing 1, the OutputCache action filter is applied to the Index() action. You also could apply this attribute to the DataController class itself. In that case, the result returned by any action exposed by the controller would be cached for 10 seconds.

The Different Types of Filters

The ASP.NET MVC framework supports four different types of filters:
  1. Authorization filters – Implements the IAuthorizationFilter attribute.
  2. Action filters – Implements the IActionFilter attribute.
  3. Result filters – Implements the IResultFilter attribute.
  4. Exception filters – Implements the IExceptionFilter attribute.
Filters are executed in the order listed above. For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.
Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.
Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Each different type of filter is executed in a particular order. If you want to control the order in which filters of the same type are executed then you can set a filter's Order property.
The base class for all action filters is the System.Web.Mvc.FilterAttribute class. If you want to implement a particular type of filter, then you need to create a class that inherits from the base Filter class and implements one or more of the IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces.

The Base ActionFilterAttribute Class

In order to make it easier for you to implement a custom action filter, the ASP.NET MVC framework includes a base ActionFilterAttribute class. This class implements both the IActionFilter and IResultFilter interfaces and inherits from the Filter class.
The terminology here is not entirely consistent. Technically, a class that inherits from the ActionFilterAttribute class is both an action filter and a result filter. However, in the loose sense, the word action filter is used to refer to any type of filter in the ASP.NET MVC framework.
The base ActionFilterAttribute class has the following methods that you can override:
  • OnActionExecuting – This method is called before a controller action is executed.
  • OnActionExecuted – This method is called after a controller action is executed.
  • OnResultExecuting – This method is called before a controller action result is executed.
  • OnResultExecuted – This method is called after a controller action result is executed.
In the next section, we'll see how you can implement each of these different methods.

Creating a Log Action Filter

In order to illustrate how you can build a custom action filter, we'll create a custom action filter that logs the stages of processing a controller action to the Visual Studio Output window. Our LogActionFilter is contained in Listing 2.
Listing 2 – ActionFilters\LogActionFilter.cs
using System;
using System.Diagnostics;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1.ActionFilters
{
     public class LogActionFilter : ActionFilterAttribute

     {
          public override void OnActionExecuting(ActionExecutingContext filterContext)
          {
               Log("OnActionExecuting", filterContext.RouteData);       
          }

          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
               Log("OnActionExecuted", filterContext.RouteData);       
          }

          public override void OnResultExecuting(ResultExecutingContext filterContext)
          {
               Log("OnResultExecuting", filterContext.RouteData);       
          }

          public override void OnResultExecuted(ResultExecutedContext filterContext)
          {
               Log("OnResultExecuted", filterContext.RouteData);       
          }


          private void Log(string methodName, RouteData routeData)
          {
               var controllerName = routeData.Values["controller"];
               var actionName = routeData.Values["action"];
               var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
               Debug.WriteLine(message, "Action Filter Log");
          }

     }
}
        
In Listing 2, the OnActionExecuting(), OnActionExecuted(), OnResultExecuting(), and OnResultExecuted() methods all call the Log() method. The name of the method and the current route data is passed to the Log() method. The Log() method writes a message to the Visual Studio Output window (see Figure 2).
Figure 02: Writing to the Visual Studio Output window (Click to view full-size image)
The Home controller in Listing 3 illustrates how you can apply the Log action filter to an entire controller class. Whenever any of the actions exposed by the Home controller are invoked – either the Index() method or the About() method – the stages of processing the action are logged to the Visual Studio Output window.
Listing 3 – Controllers\HomeController.cs
using System.Web.Mvc;
using MvcApplication1.ActionFilters;

namespace MvcApplication1.Controllers
{
     [LogActionFilter]
     public class HomeController : Controller
     {
          public ActionResult Index()
          {
               return View();
          }

          public ActionResult About()
          {

               return View();
          }
     }
}
        

Summary

In this tutorial, you were introduced to ASP.NET MVC action filters. You learned about the four different types of filters: authorization filters, action filters, result filters, and exception filters. You also learned about the base ActionFilterAttribute class.
Finally, you learned how to implement a simple action filter. We created a Log action filter that logs the stages of processing a controller action to the Visual Studio Output window.

Types of ASP.NET MVC 3 Action Results

This will surprise some of you that know me or the company I work for, but not all of our staff are experts with ASP.NET MVC. In fact, I am hoping that the couple who aren’t will read this post and learn a little bit more about the topic.
Since the actions of controllers in MVC are dealt with constantly, I think it is a good place to start. This post is going to briefly describe the different types of results that are available to you in ASP.NET MVC 3. I will show some of the code that makes them work, which should make all of this seem a lot less complicated.
When creating new controllers in ASP.NET MVC 3, they will come with one or more actions by default. This depends on whether you selected a template which includes extras for you. The Empty controller template comes with an Index action with a return value of type ActionResult.

ActionResult

The action result is a very generic return value for an action. This is because it is the abstract base class for other types of actions. It is actually a very simple class having only one method that needs implementing.
public abstract class ActionResult
{
    public abstract void 
        ExecuteResult(ControllerContext context);
}
Inheriting from the ActionResult are the following classes:
  • ContentResult
  • EmptyResult
  • FileResult
  • HttpStatusCodeResult
  • JavaScriptResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase
These are the classes that inherit from ActionResult indirectly:
  • FileContentResult
  • FilePathResult
  • FileStreamResult
  • HttpNotFoundResult
  • HttpUnauthorizedResult
  • PartialViewResult
  • ViewResult

ViewResultBase, ViewResult, and PartialViewResult

The ViewResult is the most common concrete type you will be returning as a controller action. It has an abstract base class called ViewResultBase, which it shares with PartialViewResult.
It is in the ViewResultBase abstract base class that we get access to all of our familiar data objects like: TempData, ViewData, and ViewBag.
PartialViews are not common as action results. PartialViews are not the primary thing being displayed to the user, that is the View. The partial view is usually a widget or something else on the page. It’s usually not the primary content the user sees.
This is the common return syntax, and it means that you’re returning a ViewResult.
return View();
That is actually a call to the base Controller.View method, which is just going to call through with some defaults.
protected internal ViewResult View()
{
    return View(null, null, null); 
}
 
The beauty of ASP.NET MVC is actually in its simplicity though, because all that really did was create our ViewResult for us. If we take a look at the method that is being called you can see that we’re just taking a little shortcut and keeping our action clean of this code we would otherwise repeat every time we wanted a ViewResult.
protected internal virtual ViewResult View(
    string viewName, string masterName, object model) 
{
    if (model != null) 
    { 
        ViewData.Model = model; 
    }
 
    return new ViewResult 
    {
        ViewName = viewName,
        MasterName = masterName,
        ViewData = ViewData, 
        TempData = TempData
    }; 
} 
Notice how simple that really is. All it did was put the model data in if we specified it, give the ViewResult the Controller properties that we set already, and assign the viewName and masterName.
Keep in mind, that we already saw that the abstract method in the ActionResult was the ExecuteResult method. The last two things to look at with the ViewResultBase are the ExecuteResult method and its abstract method FindView, which is being implemented by ViewResult and PartialViewResult.
public override void ExecuteResult(
    ControllerContext context)
{
    if (context == null) 
    { 
        throw new ArgumentNullException("context"); 
    }
    if (String.IsNullOrEmpty(ViewName)) 
    { 
        ViewName = context.RouteData
            .GetRequiredString("action");
    }

    ViewEngineResult result = null; 

    if (View == null) 
    { 
        result = FindView(context); 
        View = result.View;
    } 

    TextWriter writer = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(
        context, View, ViewData, TempData, writer);
    View.Render(viewContext, writer); 

    if (result != null) 
    { 
        result.ViewEngine.ReleaseView(context, View); 
    }
} 
This method is also not very complicated. It checks to make sure we have context, and then if we don’t have the ViewName then we get that information from the RouteData. Remember in MVC that the name of action is included in the RouteData, so we can use that as the default view name. This means that in the Index action, if we just call View(), it will give us a ViewName of “Index”.
We then get the view we’re looking for by calling the FindView abstract method, which means we’re calling through to either ViewResult and PartialViewResult. Those I am not going to get into the guts of, but each one is going to try to find the correct view based on the name using its collection of ViewEngines.
Once we have the view, we are able to tell it to render itself using the context and the TextWriter we give to it.
That’s all there is to a ViewResult.

ContentResult

The content result lets you define whatever content you wish to return. You can specify the content type, the encoding, and the content. This gives you control to have the system give whatever response you want. This is a good result to use when you need a lot of control over what you’re returning and it’s not one of the standards.
Its ExecuteResult override is extremely simple.
public override void ExecuteResult(ControllerContext context) 
{ 
    if (context == null) 
    {
        throw new ArgumentNullException("context"); 
    } 

    HttpResponseBase response = context.HttpContext.Response; 

    if (!String.IsNullOrEmpty(ContentType)) 
    {
        response.ContentType = ContentType;
    } 
    if (ContentEncoding != null) 
    {
        response.ContentEncoding = ContentEncoding; 
    } 
    if (Content != null) 
    {
        response.Write(Content); 
    }
}
It just puts what you specified directly into the response.

EmptyResult

There is no simpler result than the EmptyResult. All it does is override the ExecuteResult method and since that method is void, the method is empty.
I really don’t think I need that code snippet for this one.

FileResult, FileStreamResult, FilePathResult, and FileContentResult

If you want specific actions to send files as the response, then the FileResult is for you. Sadly, the FileResult is abstract, so you’ll need to use one of the inheriting classes instead. Each of these actually just overrides the WriteFile method for the abstract FileResult class.
If you want to just send the contents of the file back with the array of bytes for the file, then you want the FileContentResult. It uses the response’s OutputStream and writes those bytes directly into the stream sending it down to the user.
If you want to transmit the file using its name, you can use FilePathResult, which will call through a whole bunch of layers finally down to the HttpResponse. Once there it is going to create a new FileStream for your file and write the stream to the response allowing the file to be accessed from your action.
If you’ve already got a stream you can use the FileStreamResult, which will read all of the data from your stream and then write it into the OutputStream to be send back in the response.
These really aren’t all that complicated, but if you want to have control over the file downloads in your application, this is a great way to do it. These give you the power to put any code you want in your action before you give back the FileResult.

HttpStatusCodeResult

The HttpStatusCodeResult is as simple as the ContentResult. In fact, the two are quite similar since they both just directly modify the response object.
This one lets you return any StatusCode you want and you can include a StatusDescription for specifics.
public override void ExecuteResult(ControllerContext context)
{ 
    if (context == null)
    {
        throw new ArgumentNullException("context"); 
    } 

    context.HttpContext.Response.StatusCode = StatusCode; 
    if (StatusDescription != null)
    {
        context.HttpContext.Response
            .StatusDescription = StatusDescription;
    }
} 
See how simple that is? It’s basically just two lines of code with some null checking included.

HttpNotFoundResult and HttpUnauthorizedResult

These two results are actually just implementing the HttpStatusCodeResult, which means that they are very simple and just set the StatusCode to 404 for the HttpNotFoundResult and 401 for the HttpUnauthorizedResult.

JavaScriptResult

About as simple as plenty of the others, this is just a quick way of getting JavaScript returned from a action. It’s similar to the ContentResult, but it has the ContentType hardcoded to “application/x-javascript” and just writes out the Script property.
public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    } 

    HttpResponseBase response = context.HttpContext.Response; 
    response.ContentType = "application/x-javascript"; 

    if (Script != null)
    { 
        response.Write(Script);
    }
}

JsonResult

This one is a bit more complex, but still not very. It also has hardcoded its ContentType, but what makes it a bit more complex is that it uses a hardcoded JavaScriptSerializer to serialize the JSON data before writing it directly to the response.
public override void ExecuteResult(ControllerContext context)
{ 
    if (context == null)
    { 
        throw new ArgumentNullException("context");
    } 
    if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
        String.Equals(context.HttpContext.Request.HttpMethod, 
            "GET", StringComparison.OrdinalIgnoreCase)) 
    {
        throw new InvalidOperationException(
            MvcResources.JsonRequest_GetNotAllowed);
    } 

    HttpResponseBase response = context.HttpContext.Response; 
 
    if (!String.IsNullOrEmpty(ContentType)) {
        response.ContentType = ContentType; 
    }
    else {
        response.ContentType = "application/json";
    } 
    if (ContentEncoding != null) {
        response.ContentEncoding = ContentEncoding; 
    } 
    if (Data != null) {
        JavaScriptSerializer serializer = 
            new JavaScriptSerializer(); 
        response.Write(serializer.Serialize(Data));
    }
}

RedirectResult and RedirectToRouteResult

These to are a little bit more complex, but both are ways of redirecting. Each one can either be a permanent or temporary redirect and they both just use the Redirect methods on the Response object.
For redirecting to a route, it is going to generate a URL to the route using the UrlHelper’s GenerateUrl method. For the RedirectResult it is instead going to use the UrlHelpers GenerateContentUrl method.
Either of these two are useful, and both will maintain your TempData if you need to pass something along with the redirect, all you have to do is put it in TempData.

Conclusion

I hope you’ve learned that the results of actions in MVC are not actually very complicated, but there is a lot you can do with them. You’re not being forced into just displaying views. You have a lot more control than that. None of them were that complicated were they? The code under the hood is not always complicated, so it’s worth taking a look from time to time. If you examine how something is working, it’s often far easier to use it.

Change Date object to any type of Date Format in MVC Controller

Java Script
----------------------
Date.prototype.customFormat = function(formatString) {
    var YYYY, YY, MMMM, MMM, MM, M, DDDD, DDD, DD, D, hhh, hh, h, mm, m, ss, s, ampm, AMPM, dMod, th;
    var dateObject = this;
    YY = ((YYYY = dateObject.getFullYear()) + "").slice(-2);
    MM = (M = dateObject.getMonth() + 1) < 10 ? ('0' + M) : M;
    MMM = (MMMM = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][M - 1]).substring(0, 3);
    DD = (D = dateObject.getDate()) < 10 ? ('0' + D) : D;
    DDD = (DDDD = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][dateObject.getDay()]).substring(0, 3);
    th = (D >= 10 && D <= 20) ? 'th' : ((dMod = D % 10) == 1) ? 'st' : (dMod == 2) ? 'nd' : (dMod == 3) ? 'rd' : 'th';
    formatString = formatString.replace("#YYYY#", YYYY).replace("#YY#", YY).replace("#MMMM#", MMMM).replace("#MMM#", MMM).replace("#MM#", MM).replace("#M#", M).replace("#DDDD#", DDDD).replace("#DDD#", DDD).replace("#DD#", DD).replace("#D#", D).replace("#th#", th);
    h = (hhh = dateObject.getHours());
    if (h == 0) h = 24;
    if (h > 12) h -= 12;
    hh = h < 10 ? ('0' + h) : h;
    AMPM = (ampm = hhh < 12 ? 'am' : 'pm').toUpperCase();
    mm = (m = dateObject.getMinutes()) < 10 ? ('0' + m) : m;
    ss = (s = dateObject.getSeconds()) < 10 ? ('0' + s) : s;
    return formatString.replace("#hhh#", hhh).replace("#hh#", hh).replace("#h#", h).replace("#mm#", mm).replace("#m#", m).replace("#ss#", ss).replace("#s#", s).replace("#ampm#", ampm).replace("#AMPM#", AMPM);
};

How to Create Cursor

declare @tempt table
(
ID int null,
Name varchar(100) null
)
DECLARE @vendor_id int, @vendor_name nvarchar(50),
    @message varchar(80), @product nvarchar(50);
PRINT '-------- Vendor Products Report --------';
-- Declare Cursor – untill it deallocate
-- You Con’t declare another cursor with same name.
DECLARE vendor_cursor CURSOR FOR
SELECT ID,Ag_Fname
from AgentMaster
OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor
INTO @vendor_id, @vendor_name
WHILE @@FETCH_STATUS = 0
BEGIN
   
    SELECT @message = '----- Vendor: ' +
        @vendor_name
    PRINT @message
    insert INTO @tempt values (@vendor_id, @vendor_name)
   
    FETCH NEXT FROM vendor_cursor
    INTO @vendor_id, @vendor_name
END
CLOSE vendor_cursor;
select * from @tempt
-- Deallocate Cursor
DEALLOCATE vendor_cursor;

How To Create A Trigger.

Trigger is procedural code that is automatically executed in response to certain events on a specific table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.
Triggers are of 3 types in SQL Server 2005:

1. DML Triggers
   - AFTER Triggers
   - INSTEAD OF Triggers { INSERT, UPDATE, and DELETE }
2. DDL Triggers {if any schema change.}
3. CLR Triggers
Create trigger Delete_TrigerName
on ReferanceTable
for Delete
as
--Checking for Table exist.
--if Table not exist then create a table with same schema of operation table
if NOT EXISTS(SELECT * FROM information_schema.tables
                              WHERE TABLE_CATALOG = 'DATABASE-NAME'
                              AND table_name = 'Backup-TABLE-NAME')
begin
-- Copy full table with creating table of copied table schema                      
     select * into  Backup-TABLE-NAME from deleted
--Set Identity column Off. Otherwise we will not able to track the                                                                                                                                previous position of table.
     SET IDENTITY_INSERT [Backup-TABLE-NAME ] off
end
else
begin
       INSERT INTO Backup-TABLE-NAME ([Column1],[ Column2],[ Column3])
       SELECT [Column1],[ Column2],[ Column3]
       FROM deleted
end
--select * from Backup-TABLE-NAME
--select * from AgentMaster
--delete from AgentMaster where Ag_ApplNo=22

Pan Number format and Duplication entry validation in KendoUi

Checking from database using json and Controler's action where controler is Validation and Action is CheckPanNo . Then we check format using test function. and error message set to messages section of  kendoValidator function.

Java Script

 

///Pan No Duplication checking
        var validatable = $("#Pan").kendoValidator({
            onfocusout: true,
            onkeyup: true,
            rules: {
                PanNo: function (input) {
                    $.post("/Validation/CheckPanNo", { PanNo: $("#Pan").val() }, function (data) { b1 = data; })
                    return b1;
                },
                PanFormat: function (input) {
                    // return validatePanCard('Pan');
                    var value = input.val();
                    var regex1 = /^[A-Z]{5}\d{4}[A-Z]{1}$/;
                    if (!regex1.test(value) || value.length != 10) {
                        return false;
                    }
                    return true;
                }
               
            },
            messages: {
                PanNo: "Already Exist",
                PanFormat: "Not a currect format"
            }
        }).data("kendoValidator");

 Action

 

[HttpPost]
        public JsonResult CheckPanNo(string PanNo)
        {
            bool IsOk = projectRepository.CheckPanNumber(PanNo);
            return Json(IsOk, JsonRequestBehavior.AllowGet);
        }

How to Binding Dropdown Using Knockout JS

Using jquery, we access date from Action called Ko_ShowBranch in a controller caller ListObject. This action access data from database using a function called ShowAll_Branch() and to return Json result in text and value property we write below line this way.
ShowAll_Branch().Select(p => new { text =p.BranchName , value = p.ID.ToString() });
In Html Value property and Text property are set using optionsValue: and optionsText:
Javascript
 viewModel = {
        Branch: ko.observableArray()
    };
    $(function () {
        $.getJSON('http://localhost:3400/ListObject/Ko_ShowBranch', null
          function (response)  {
            viewModel.Branch(response);
        });
         ko.applyBindings(viewModel);
    });
Html
 <select data-bind="options: Branch, optionsCaption: 'Choose Branch...',
            optionsValue: function(item) { return item.value; },
            optionsText: function(item) { return item.text; }" id="Branch" name="Branch">   </select>
Controler
 public JsonResult Ko_ShowBranch()
        {
            var result = projectRepository.ShowAll_Branch().Select(p => new { text =                      p.BranchName, value = p.ID.ToString() });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

Kendo - KnockOut Grid Bind

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

<link href="@Url.Content("~/Content/kendo.common.min.css")" rel="stylesheet" type="text/css" />

<link href="@Url.Content("~/Content/kendo.blueopal.min.css")" rel="stylesheet" type="text/css" />


<script src="@Url.Content("~/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>

<script src="../../Scripts/knockout-2.2.0.debug.js" type="text/javascript"></script>

<script src="../../Scripts/kendo.all.min.js" type="text/javascript"></script>

<script src="../../Scripts/knockout-kendo.min.js" type="text/javascript"></script>


HTML

                                              


<div data-bind='kendoGrid:gridConfig'></div>  

                                               

JavaScript


<script language="javascript" type="text/javascript">

$(document).ready(function () {
      
        $.ajaxSetup({ async: false });
        //var Data= [{ "ShipCity": "Kolkata", "ShipName": "Pinaki GROUP" }, { "ShipCity": "Mumbai", "ShipName": "Pinaki SOL"}];
        var Data = null;
        function DataFunction() {
            $.post("/BkCode/BookResult", null, function (d) {
                Data = d;
            });
            return Data;
        }
      
        var ViewModel = function () {
            this.gridConfig = {
                data: null,
                dataSource: {
                    type: "odata",
                    data: DataFunction(), //This is use to access data from database using jQuery
                                          //   and return data in Json format
                    //data: Data,
                    schema: {
                        model: {
                            fields: {
                                ShipCity: {
                                    type: "string"
                                   
                                },
                                ShipName: {
                                    type: "string"
                                }
                            }
                        }
                    },
                    pageSize: 10 //,
                    //serverPaging: true,
                    //serverFiltering: true,
                    //serverSorting: true
                },
                columns: [{
                    field: "ShipCity",
                    title: "Id",
                    filterable: false
                },
                {
                    field: "ShipName",
                    title: "Company Name",
                    filterable: true
                },
                {
                    command: ["edit", "destroy"],
                    filterable: false
                }] ,
                height: 550,
                scrollable: false,
                pageable: true,
                sortable: true,
                groupable: true,
                filterable: true,
                editable: "inline", //popup
                save: function () {
                    this.refresh();
                }
            };
        };
        ko.applyBindings(new ViewModel());
    })

</script>

C#

public JsonResult BookResult()
        {
            var result = from s in bk.GetPrmCompanies()
                         select new book{
                             ShipCity = s.Id,
                             ShipName = s.CoNames
                         };
            DB.Configuration.ProxyCreationEnabled = false;
            return Json(result, JsonRequestBehavior.AllowGet); //Content(sd, "text/xml");
        }