Reader Level:
Articles

JsAction with T4 Template

By Yusuf Karatoprak on June 06, 2013
JsAction’ve been providing us to access Mvc Controller Actions with parameters intellisense. I would like to show you how to do use JsAction in big project with T4 File.
  • 0
  • 0
  • 13755
Download Files:
 

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.
 

1.png

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!
 
2.jpg

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:
 
 <#@ template language="C#" Debug="true" #>

<#@ output extension=".js" #>
<#@ assembly name="System.Xml"#>
<#@ assembly name="Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #>
<#@ assembly name="Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #>
<#@ import namespace="Microsoft.SqlServer.Management.Smo" #>
<#@ import namespace="System.Collections.Generic" #>
<#    Dictionary <string,string> DataTypes=new Dictionary<string,string>()
        {
            {"varbinary","Byte[]"},    
            {"binary","Byte[]"},
            {"text","String"},
            {"bit","boolean"},
            {"smallint","Byte"},
            {"int","int"},
            {"bigint","long"},
            {"nvarchar","String"},
            {"datetime","DateTime"},
            {"decimal","decimal"},
            {"char","string"},
            {"varchar","string"},
            {"nchar","string"},
            {"numeric","decimal"},
            {"image","byte[]"},
            {"ntext","string"},
            {"money","decimal"},
            {"real","decimal"}
            };
    Server srv =
new Server("PC");
    srv.ConnectionContext.LoginSecure = false;
srv.ConnectionContext.Login = "sa";
srv.ConnectionContext.Password = "@xxxx";
       Database database = new Database(srv,"NORTHWND");
       database.Refresh();
int i =0;
       foreach (Table tab in database.Tables)
    {
        if (tab.Name!="sysdiagrams")
        {
#>
JsActions.<#=tab.Name.ToString()#> ={
<#                  foreach (Column col in tab.Columns)
            { i++;
#>
<#= tab.Name.ToString()#>By<#=col.Name#>: function (<#=col.Name#>) {///<param name="<#=col.Name#>" type = "<#=DataTypes[col.DataType.ToString()]#>"></param>
}<#                if(i<tab.Columns.Count){ #> , <#} else { i=0;} #>
<#                  }#>
}<#  }}#>

Intellisense is Great!

jsactionAnime.gif


 

 

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.Findsomething method will help you to access json elements data.
 
       JsActions.Student.GetByName('Yusuf').then(function(data) {
             alert(findSomething(data, 'Surname'));
        });
    function findSomething(object, name) {
            if (name in object) return object[name];
            for (key in object) {
                if ((typeof (object[key])) == 'object') {
                    var t = findSomething(object[key], name);
                    if (t) return t;
                }
            }
            return null;
        }

Also EveryThings OK in Action Side!

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

4.png
 

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

3.png
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 CallingAjaxWith 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()); });

 

Summary                 

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.

References:

http://www.dotnet-programming.com/post/2012/04/02/Calling-MVC-Action-from-Javascript.aspx

COMMENT USING

Trending up