JsAction with T4 Template

Nuget Say That: JsAction is a simple and lightweight RouteHandler for ASP.NET MVC and WEBAPI that will generate automatic jQuery based Javascript and provide a direct way to call MVC and WEBAPI Action Methods using a single data annotation.


This is a RouteHandler method C# Controller to JS !
In this post I'II show you how you can use Jquery to call MVC Action methods which produce Json data. Json data can be just as effective as actual weapon.Firstly you need JsAction.Writing JsAction attributes both js handshake file and add attribute Csharp Controller side. But you would like to use jsAction in big Project.When writing HANDSHAKE js file (script.js) manually, You will afford more time.i've been decided to use T4 template.Using this template is easy. You just need to apply the right style T4 coding which is depended on the T4 context. The article should be organized into multiple sections. Lets see steps! 

Developing T4 Template

Creating a list is easy:
  • Write access code Nortwind db( I prefer NorthWind)
  • Design js file creater code
  • Press Ctrl+S to generate Js file
  • Copy paste other js files.
T4 Code

You must produce Js handshake file in big project. I think it is useful to reduce time expenses. I would like to generate a js file that is a kind of handshake template JsAction is using this js file to communicate MVC Controller's Actions.Let's talk about code. Code snippets are formatted like below:
  1. <#@ template language="C#" Debug="true" #>  
  3. <#@ output extension=".js" #>  
  4. <#@ assembly name="System.Xml"#>  
  5. <#@ assembly name="Microsoft.SqlServer.Smo, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #>  
  6. <#@ assembly name="Microsoft.SqlServer.ConnectionInfo, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #>  
  7. <#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #>  
  8. <#@ import namespace="Microsoft.SqlServer.Management.Smo" #>  
  9. <#@ import namespace="System.Collections.Generic" #>  
  10. <#    Dictionary <string,string> DataTypes=new Dictionary<string,string>()  
  11.         {  
  12.             {"varbinary","Byte[]"},      
  13.             {"binary","Byte[]"},  
  14.             {"text","String"},  
  15.             {"bit","boolean"},  
  16.             {"smallint","Byte"},  
  17.             {"int","int"},  
  18.             {"bigint","long"},  
  19.             {"nvarchar","String"},  
  20.             {"datetime","DateTime"},  
  21.             {"decimal","decimal"},  
  22.             {"char","string"},  
  23.             {"varchar","string"},  
  24.             {"nchar","string"},  
  25.             {"numeric","decimal"},  
  26.             {"image","byte[]"},  
  27.             {"ntext","string"},  
  28.             {"money","decimal"},  
  29.             {"real","decimal"}  
  30.             };  
  31.     Server srv = new Server("PC");  
  32.     srv.ConnectionContext.LoginSecure = false;  
  33. srv.ConnectionContext.Login = "sa";  
  34. srv.ConnectionContext.Password = "@xxxx";  
  35.        Database database = new Database(srv,"NORTHWND");  
  36.        database.Refresh();  
  37. int i =0;  
  38.        foreach (Table tab in database.Tables)  
  39.     {  
  40.         if (tab.Name!="sysdiagrams")  
  41.         {#>  
  42. JsActions.<#=tab.Name.ToString()#> ={  
  43. <#                  foreach (Column col in tab.Columns)  
  44.             { i++; #>  
  45. <#= tab.Name.ToString()#>By<#=col.Name#>: function (<#=col.Name#>) {///<param name="<#=col.Name#>" type = "<#=DataTypes[col.DataType.ToString()]#>"></param>  
  46. }<#                if(i<tab.Columns.Count){ #> , <#} else { i=0;} #>  
  47. <#                  }#>  
  48. }<#  }}#>  

Intellisense is Great!




The intellisense feature works fine.HandShake xml documentation give ability to access MVC Razor Controller's Action from Js side. We reduce long ajax calling to one sentence with great intellisense!Also you can access Json element to parse html elements.Find something method will help you to access json elements data.
  1. JsActions.Student.GetByName('Yusuf').then(function(data) {  
  2.       alert(findSomething(data, 'Surname'));  
  3.  });  
  4. ction findSomething(object, name) {  
  5.      if (name in object) return object[name];  
  6.      for (key in object) {  
  7.          if ((typeof (object[key])) == 'object') {  
  8.              var t = findSomething(object[key], name);  
  9.              if (t) return t;  
  10.          }  
  11.      }  
  12.      return null;  
  13.  }  

Also EveryThings OK in Action Side!

When Calling action from js side.Every actions will run perfectly.


Also look produced xml type document.You can access produced methods in client side.

If you look below; you can see more flexable code in JsAction Side. JsAction behave a kind of proxy which is to make it easy as a single function call .Codes in client side don't monitor ajax event also give us plural visualization to developer to keep track of code flows.More understandable coding separates ajax from business logic.

Reduce and convert  proxy ajax events

Classic CallingAjax With JsAction
var opts = {
url: "/Home/Yusuf",
async: true,
cache: true,
type: "GET",
data: $.toDictionary({
st: st,
a: a,
b: b

JsActions.Home.Yusuf(67, 9).then(function (data) { alert(data.toString()); });



You've learned how to use JsAction in big project via T4 template. T4 will help us produce handshake file (Xml document but saved as js) which is helpful to see actions in js side. You can produce more flexible structures. JsAction gives us opportunity to read client side codes perfectly. But the most advantages of JsAction can call Controllers' action dynamically (JsActions.Home.Yusuf( ….) in client side with intellisense with one sentence. Fluent and dynamic coding are perfect.



Similar Articles