C# – Mocking a method to return a different value when called a second time using Moq

The “My Adventures in Coding” blog had a great post on utilizing Moq to return different resultsets from one method call. Depending on the setup you need, there are a few options. Using a Queue was an excellent approach and worked great in a test I just did. Check out this post if you are using Moq.

My Adventures in Coding

I have been using Moq as my primary mocking framework in C# for several years now. Overall I really like it, the syntax is easy to read, the mock setup is straight forward, etc. However, there are a few cases I need to mock infrequently and I always forget how to do the setup. Often because I am cycling between Scala, Python, and C#. So in this post I am just listing those three cases in hopes they may help others, yet at the same time as a reference to myself!

So for this example, first here is my example service that we will be mocking in our tests:

Return a different value the second time a mocked method is called

Let’s say I have a call in a service that returns the next item to process, such as pulling in customer requests from a queue that need to be…

View original post 401 more words

HTML 5 Document Navigation in ASP.NET MVC

In this post we are going to create a widget of sorts for document page navigation arrows that appear on the left and right sides of the screen. Ever go to a news site and see arrows on the side of the page that allow you to click between articles? Sometimes that is a useful feature to add to an app, so we are going to do so as a helper method defined as the following.


@GlobalHelpers.LeftArrow("Left")
@GlobalHelpers.RightArrow("Right")

It’s important to note that I haven’t wired up the arrows to navigational actions, but it wouldn’t be difficult to do so. I’ve defined some global helpers in the (App_Code) folder that output some HTML:


@helper LeftArrow(string title, string icon = "glyphicons-chevron-left")
{
   <div class="doc-left-arrow-container">
      <div id="DocLeftNavButton" class="doc-left-arrow-block" title="@title">
         <span class="glyphicons @icon"></span>
      </div>
   </div>
}

@helper RightArrow(string title, string icon = "glyphicons-chevron-right")
{
   <div class="doc-right-arrow-container">
      <div id="DocRightNavButton" class="doc-right-arrow-block" title="@title">
         <span class="glyphicons @icon"></span>
      </div>
   </div>
}

These helpers output a template that gets transformed to left and right fixed arrows via the following CSS.

.doc-left-arrow-container {
   width: 50px;
   top: 200px;
   left: 0px;
   height: 50px;
   position: fixed;
   font-size: 36px;
}

.doc-left-arrow-block {
   border: 1px solid black;
   border-left: 0 !important;
   border-top-right-radius: 4px;
   border-bottom-right-radius: 4px;
}

.doc-left-arrow-block .glyphicons {
   margin-top: 10px;
}

.doc-right-arrow-container {
   width: 50px;
   top: 200px;
   right: 0px;
   height: 50px;
   position: fixed;
   font-size: 36px;
}

.doc-right-arrow-block {
   border: 1px solid black;
   border-top-left-radius: 4px;
   border-bottom-left-radius: 4px;
}

   .doc-right-arrow-block .glyphicons {
      margin-top: 10px;
   }

The idea here being that we are using absolute positioning to affix these documents to the left and right side. Albeit not perfect, it can be easily tweaked to utilize media groups to shrink in size, turn itself off with mobile dimensions, and provide other features. It would also be easy to specify a URL parameter in the helper method as well, as a means to define a URL for link redirection.

Solving Limitations with the Kendo AutoComplete Control

The Kendo AutoComplete control provides a great user interface for type ahead functionality. It works seamlessly with bound JSON data from an AJAX data source and provides a tidy, yet customizable, view of the data. Some of the functionality of the behavior is customizable, and it exposes a decent set of events. You can view the demo of the control here.

Even though the control has a decent number of features, the API is still really lax in offering you specific information that was selected. Even though you may have sent an array of JSON object with 20 properties, you can only access the selected value (please vote for my request to change that behavior). However, there is a way to work around that limitation, which is to create a custom template. The autocomplete control has a template attribute that takes a string for the UI to use as each data item. Internally in this template, the “data” object refers to the data source bound to this template, and is a way to display multiple properties of data in the same line item.

Let’s briefly look at the Kendo AutoComplete basic configuration, which is the following. (Note that this article expects you to have a familarity with the control; I won’t be going over it in detail here.)

$("#txtName").kendoAutoComplete({
   placeholder: 'Name Search',
   delay: 500,
   dataTextField: 'Name',
   dataValueField: 'ID',
   filter: 'contains',
   minLength: 3,
   dataSource: ..
 });

Out of the box, this auto complete wires up to a data source, matching a Name as the text and ID as the value. The kendo datasource ties the control to the backend data store (an example for another time). Now suppose you had this JSON:

[
{ "ID": 1, "Name": "Ted", "Address": "101 Test Rd", "Phone": "555-555-5555", "Email": "test@test.com" },
{ "ID": 2, "Name": "Bob", "Address": "21 Other Rd", "Phone": "567-555-5555", "Email": "test2@test.com" }
]

When the type ahead behavior occurs, after typing 3 characters, the control sends back a request with the current text and displays the response in the dropdown. But it only shows the value in the Name property (“Ted”, “Bob”).

This is where the template property comes into play

$("#txtName").kendoAutoComplete({
   .
   .
   template:
   '<div class="item" data-address="#:data.Address#" data-phone="#:data.Phone#" data-email="#:data.Email#">' +
   '<div><strong>#:data.Name#</strong><div>' +
   '# if (data.Address != null) { # <div>#:data.Address#</div> # } #' +
   '<div>#:data.Phone#, #:data.Email#</div>' +
   '</div>',
   dataSource: ..
 });

With the template property, this provides a custom UI to the user. You can see the “data” object reference; this is the actual underlying JSON data at execution time. Templates work great but we still have the unfortunate problem of not being able to access the “Address”, “Phone”, or “Email” attributes of the JSON object outside of displaying in the list. This is where the data attributes on the root DIV come into play. Using those attributes, we can extract them out from the selected item during the select event:

select: function (e) {
   var $item = e.item.find("div.item");
   $("#txtAddress").val($item.data("address"));
   $("#txtPhone").val($item.data("phone"));
   $("#txtEmail").val($item.data("email"));
}

On select, e.item refers to the HTML representing the current item. Finding the DIV wrapper we have our data attributes on, the data can be extracted and pushed somewhere. In this case the fields are populated into an edit form.

Hopefully this was a good overview as a means to grab additional useful, meaningful information that I could not find available anywhere else in the Kendo AutoComplete control API. Using this technique, we can gain additional meaningful information to populate another portion of the UI when something changes.

My Time As a Microsoft MVP

In the early 2000’s, I was working for a State agency in Pennsylvania in a .NET development role.  I’ve always been fascinated by programming on many levels: I really liked to learn the nuts and bolts of the framework, as well as the ability to create something – albeit digitally.  I tried to learn as much as I possibly could; I’d read tech books, read web sites, and post on forums.  I was pretty active specifically on the ASP.NET forums.

Sometime in 2007, I received an email from Microsoft in regards to the MVP program!  I was shocked when I got the email.  I spent a lot of time there, posting questions in hoping to gain insight and trying to provide answers to assist the technical community.  When the honor was confirmed, I was really appreciative of it; it was a great honor.

Fast forward 10 years later:

mvptenyears

I’ve been very blessed individual.  I’ve gotten to offer my time and skills to the community.  I’ve gotten to meet individuals at Code Camps or Give Camps.  I’ve gotten to write for DevProConnection Magazine, ASP Alliance, DotNetSlackers, DotNetJohn,  this blog, and other places.   I considered speaking for Pluralsight, but I’m not the greatest speaker.  Additionally, I’ve gotten to be involved in interesting projects over the years, as I shifted from government work to consulting work to product development.  I’ve gotten to help analyze and solve other people’s technical (and sometimes personal) problems.

Life really comes at you fast some times.  It doesn’t seem like long ago that our 3 children entered our world, but the facts remain the same (ages 11, 9, 7).  We adopted our beautiful daughter from China, and we are in the process of adopting our son (also from China).  My kids have been involved in school plays, baseball games, soccer practices and games, basketball games, holiday events, church activities, school events and more.  As my career progressed, my workload got bigger, my involvements became greater, and my stresses increased.  I burned out a few times along the way, my free time dwindled between work, an ever growing family, and general increased demands.

Ten years was my run as a Microsoft MVP.  I was informed that I will not be renewed.  Microsoft was great to me and gave me many opportunities during that ten years; I am forever grateful for that.

AJAX File Uploads with HTML 5

I see on StackOverflow the question often how to upload a file via AJAX.  It turns out it is actually not that difficult. We utilize a solution using the Html 5 FileReader component. The idea is have the file reader read a PDF file contents, and transfer those contents to a hidden field (stored in the $hidden variable). A portion of the script we use is shown below.

$("#FileUpload").on('change', function (e) {
var $self = this;
var file = $self.files[0];

var fileReader = new FileReader();
fileReader.addEventListener('load', function () {
   var result = fileReader.result;
   $hidden.val(result);
});
fileReader.readAsDataURL(file);

$self.val('');
});

Once a file is read, it invokes the “load” event with the contents of the file; the contents of the file are then stored in a hidden field. Since the contents are in the HTML file, it’s possible then to send those HTML contents to the server, or be a part of a normal postback lifecycle.

The idea with “readAsDataURL” is it creates a URL like the following: “data:text/html,sdafadf34533543sefkafdsadf90809as8dfasdf90asdf9fsdf” where the contents of the PDF are really large. You’ll need to extend what is acceptable as a part of your content.

On the server side, the solution is as simple as splitting the contents after the first comma like:

//Strip off the "data:text/html," portion of the data URL posted back to the server
fileContents.Substring(fileContents.IndexOf(",") + 1);

This is one of many solutions; there are a wide variety of JQuery or other solutions out there.

Watch Your Scoping

I recently found a bug in a plugin and so I figured that would be a good time to offer a public service announcement as to why you have to be careful with scoping in JavaScript.  The plugin I’m featuring is just a quick example of the problem.  Suppose your had the following HTML snippet:


< div id="section1" class="section" >
First Button
< span id="sp1" >0< /span >
< /div >
< div id="section2" class="section" >
Second Button
< span id="sp2" >0< /span >
< /div >
< div id="section3" class="section" >
Third Button
< span id="sp3" >0< /span >
< /div >

Pretty simple. The idea of my plugin was to target the root DIV tag, and then parse down to the BUTTON and SPAN at an individual level. Now, as I think about writing this, the reality is of the situation, I should have considered the JQuery Widget API, as I think that would have been better situated for what I am about to do. I was under the gun to get this feature completed, and this solution was not optimal, but it worked and did get the job done. Anyway, the JQuery plugin is below:

$.fn.parse = function() {
  return this.each(function() {
    var spn = $(this).find("span");
    btn = $(this).find("button");
    
    btn.on("click", function(e) {
       var n = parseFloat(spn.html());
       n += 1;
       spn.html(n);
    
       btn.html(btn.html() + "(clicked)");
    });
  });
}

The idea is that the span and button are retrieved within the context of the root DIV, and when the button is clicked, both elements are updated to indicate that a click occurred. You’ll notice though, that while the span gets the proper update, the button does not (always targets the last). This is simply because the button doesn’t include “var” declaration. This means the button is scoped beyond the current context of the each() callback. Because of this, the last button was selected and thus the last button is represented in the query.

This produces the result:

jsscreenshot

Adding VAR was the immediate solution. Another reminder why you need to make sure you variables are scoped correctly.

Just to brainstorm, another solution could be to, using the current reference within the button click, access the button through the callback and even target the SPAN that way, rather than relying on variables.

You can view the Gist here.

Database T4 Templating Tricks

I love T4 templates. It’s incredible how much canned code can be generated automatically for you. T4 can not only generate static code, but it can do much more like access the database through SMO. All you need to do is define the server and database like so:

<#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<#@ assembly name="Microsoft.SqlServer.Smo" #>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>

<#@ import namespace="Microsoft.SqlServer.Management.Smo" #>
lt;#@ import namespace="Microsoft.SqlServer.Management.Common" #>


<#
 var server = new Server("localhost");
 var db = server.Databases["MYDB"];
#%gt;

In this database, suppose you have a Types table that’s static. Your types table may be a ID/Name pairing in the database, which you reference either using magic numbers (the ID since it’s static) or do a Name cross reference. With T4, instead of using numbers or strings, you could hard-code the values by querying the table and creating constants for each type:

public class Constants
{

      public partial class SettingTypes
      {
<#
         var catDS = db.ExecuteWithResults("select ID, Name from dbo.SettingTypes where Visible = 1");
         foreach (DataRow row in catDS.Tables[0].Rows)
         {
#>
         public const long <#= row["Name"].ToString() #> = <#= row["ID"].ToString() #>;
<#
         }
#>
      }
}

Above using the global DB server reference, we use the ExecuteWithResults method to run a specified query against that database, and return the results as a DataSet. The system processes the results and generates “public const long XYZ = 1” where XYZ is the name in the table, and 1 is the ID. We can generate whatever we want; for instance, you could generate just the names as strings by changing the constant to:

public const string <#= row["Name"].ToString() #> = "<#= row["Name"].ToString() #>;

This produces a result similar to the following (using our first example):

public class Constants
{
   public partial class SettingTypes
   {
       public const long AppName = 1;
       public const long URLRedirect = 2;
       .
       .
   }
}

Or as (using our second example):

public class Constants
{
   public partial class SettingTypes
   {
       public const long AppName = "AppName";
       public const long URLRedirect = "URLRedirect";
       .
       .
   }
}

Through our application, we may have had references to “AppName” or “URLRedirect” or whatever common values this type table would have (this is unfortunately a very generic example and I hope you see how it’s applicable). With our new approach, we can do:

Utilities.LookupSettingType(Constants.SettingTypes.AppName);

We now have a compiled-time reference. This helps to provide extra checking for situations where we may remove entries from the SettingsTypes table. Any code references to it would now produce a compile error.

It’s also possible to connect to a database table’s metadata too, to generate the appropriate metadata for that table. The SMO API has table and column objects, used like below that can generate the metadata to a generated class.

public partial class ApplicationDetails
{
<#
         var ncTable = db.Tables["ApplicationDetails"];

         foreach (Column column in ncTable.Columns)
         {
#>
            public const string <#= column.Name #> = "<#= column.Name #>";
<#
         }
#>
}

This would generate a class like the following:

public partial class ApplicationDetails
{
   public string ID = "ID";
   public string Name = "Name";
   public string Description = "Description";
}

Now we can change any static reference to compile time references by referring to the description column as Constants.ApplicationDetails.Description, rather than just “Description”. It’s also possible to pull other metadata in too, such as the data type and more. If you can’t get everything you need, you can try to query the INFORMATION_SCHEMA views to get any additional information.

One useful utility I created with T4 was a generic ReferenceTypes class, where all of my _Types tables are defined in a static class. This processes all of the tables in the database, generating a static reference to the name of a reference table.

public partial class ReferenceTypes
{

<# foreach (Table table in db.Tables) {
            if (table.Name.EndsWith("Types")) {
#>
         public const string <#= table.Name #> = "<#= table.Name #>";
<#
            }
         }
#>

}

Sounds good? I’ve found a lot of good uses for T4 templates; I even use it to generate a starter shell to create stored procedures, application repositories, started controllers and views for MVC, and more. I’ll touch base on that in another blog post but I hope I helped you see how useful T4 is.

There are some things you shouldn’t use it for. You shouldn’t use it for anything you expect to change dynamically. Because it’s generating classes that get compiled with the projects, you can’t change it from live code and expect the changes to be available. Any changes included are defined as of the last compilation of the application. Another thing that you may find out is you will attempt to implement some common task in T4, but T4 turns out to be not a good solution. I’ve run into this a couple of times.

All in all, T4 templates are great to generate common code and can really cut down on writing redundant code, while adding compile-type checking on reference data.

ASP.NET MVC And Client Side Lists with Kendo

In this post, I’m going to illustrate a very simple way to create client-side list-based UI’s in ASP.NET MVC. The idea with this example is to allow the ability to add a bulk number of list items that doesn’t require constantly posting back to add additional items. In this example, we’ll use Kendo UI Core framework templating capabilities, although any templating framework will do.

To start, let’s look at a very simple model:

public  class SystemTestModel
{
   public List Entities { get; set; }
}

public class SystemListEntity
{
   public string Name { get; set; }
   public string Value { get; set; }
   public bool IsDeleted { get; set; }
}

Here we have a View Model that has a list of child items. Very simple. Notice the entity has 2 properties, and an IsDeleted property, which will be illustrated later. For this example, the controller setup is simple; it reads the form posted values and rebuilds the non-deleted ones:

public ActionResult List()
{
   var model = new SystemTestModel { Entities = new List() };
   return View(model);
}

[HttpPost]
public ActionResult List(SystemTestModel model)
{
   //Remove non-deleted records - deleted from  client
   var entities = model.Entities.Where(i => i.IsDeleted == false);

   //Save entities to DB or other work
   //Reload UI
   return View(new SystemTestModel { Entities = entities.ToList() });
}

Within the view, the Name/Value pairs are rendered

<tbody id="Grid" data-last-index="@(Model.Entities.Count - 1)">
   @for (var i = 0; i < Model.Entities.Count; i++) {
     <tr>
         <td>
            <input type="text" name="@Html.NameFor(m => m.Entities[i].Name)" value="@Model.Entities[i].Name" />
            <input type="hidden" name="@Html.NameFor(m => m.Entities[i].IsDeleted)" value="@Model.Entities[i].IsDeleted" />
         </td>
         <td>
            <input type="text" name="@Html.NameFor(m => m.Entities[i].Value)" value="@Model.Entities[i].Value" />
         </td>
      </tr>
   }
</tbody>

Each server-side item is rendered using the collection-based naming syntax that MVC uses to identify collections. The name for a collection-based item looks like the server-side equivalent: Entities[X].[Field] (ie. Entities[0].Name). This is important because our client-side HTML template must do the same thing:


   <tr>
      <td>
          
          <input type="hidden" name="@Html.NameFor(m => m.Entities[-99].IsDeleted)" value="@Boolean.FalseString" />
      </td>
      <td>
          <input type="text" value="#= Value #" name="@Html.NameFor(m => m.Entities[-99].Value)" />
      </td>
   </tr>

Notice in the template the -99; the really neat thing about the NameFor helper is that the expression doesn’t need to be valid; -99 works and literally renders to the HTML as “Entities[-99].Name”. Notice that the script block is the same equivalent above, but will be used to render client-side additional elements. The HTML between the two doesn’t need to be exact, but similar. The view will use this template when the “Add” button is clicked.

What that really means is that the server may have rendered 2 name/value items, and the client can render additional pairs. Our approach is to ensure that we render the pairs in sequential order whether created from server or client, preserving that sequential order.

The view has an add button. The add button triggers the templating capability of kendo. The idea with the template is to get the HTML for the entry and replace the “-99” with the actual index. So if the server-side rendering produced 2 elements (using indexes 0 and 1), the client-side “Add” button generates items starting from index “2” and greater.

$(function () {
   //http://docs.telerik.com/kendo-ui/framework/templates/overview
   $("#NewButton").on("click", function (e) {
      var html = $("#ItemTemplate").html();
      //Get the last index, add 1 because we are adding an item at the new index
      var index = $("#Grid").data("last-index") + 1;
      $("#Grid").data("last-index", index);

      //Replace -99 with the new Index
      html = html.replace(/-99/g, index);

      //Can be used to apply data values from JS
      var template = kendo.template(html);
      var data = {}; //For now, not doing any template binding
      var content = template(data);
            
      $("#Grid").append(content);
   });
});

The first step here is get the templated HTML, and update the current index appropriately. When this UI posts back, the updated index sequence posts back the new items correctly at positions 2 and greater. When the UI reloads, we now have server-side items created from the new index, and new items can be added again.

You may have noticed the IsDeleted property; this can be used to indicate items as deleted. The UI can have a delete button, which can trigger JavaScript that can hide the entire TR tag of the item from view and update the hidden field. When posted back, a permanent delete can happen (purge from the DB if it was originally persisted).

The main goal of this approach is bulk entry of lists without having to postback to add each item, like web forms used to do.

Here is the entire View (assumes JQuery and Kendo scripts included):

@model SystemTestModel

<form action="" method="post">

   <div class="row">
      <div class="col-md-12">

         <table class="table table-bordered table-hover">
            <thead>
               <tr>
                  <th>Name
                  <th>Value
               </tr>
            </thead>
            <tbody id="Grid">
               @for (var i = 0; i < Model.Entities.Length; i++)
               {
                    <tr>
                      <td>
                         <input type="text" name="@Html.NameFor(m => m.Entities[i].Name)" value="@Model.Entities[i].Name" />
                          <input type="hidden" name="@Html.NameFor(m => m.Entities[i].IsDeleted)" value="@Model.Entities[i].IsDeleted" />
                        </td>
                         <td>
                             <input type="text" name="@Html.NameFor(m => m.Entities[i].Value)" value="@Model.Entities[i].Value" />
                           </td>
                          </tr>

               }
            </tbody>
         </table>

      </div>
   

   <div class="row">
      <div class="col-md-12">

         <button type="submit" name="Action" value="SAVE" class="btn btn-primary">
             Save 
         </button>
         <button type="button" name="Action" value="NEW" class="btn btn-default">
             New
         </button>

      </div>
   </div>

</form>

@section scripts {
   
      <script type="text/x-kendo-template">
               <tr>
                    <td>
                        <input type="text" value="#= Name #" name="@Html.NameFor(m => m.Entities[-99].Name)" />
                        <input type="hidden" name="@Html.NameFor(m => m.Entities[-99].IsDeleted)" value="@Boolean.FalseString" />
                    </td>
                     <td>
                        <input type="text" value="#= Value #" name="@Html.NameFor(m => m.Entities[-99].Value)" />
                     </td>
              </tr>
      </script>

<script type="text/javascript">
      $(function () {

         //http://docs.telerik.com/kendo-ui/framework/templates/overview
         $("#NewButton").on("click", function (e) {
            var html = $("#ItemTemplate").html();
            //Get the last index, add 1 because we are adding an item at the new index
            var index = $("#Grid").data("last-index") + 1;
            $("#Grid").data("last-index", index);

            //Replace -99 with the new Index
            html = html.replace(/-99/g, index);

            //Can be used to apply data values from JS
            var template = kendo.template(html);
            var data = {}; //For now, not doing any template binding
            var content = template(data);
            
            $("#Grid").append(content);
         });

      });
   </script>

}

And Controller:

public class SystemListEntity
   {
      public string Name { get; set; }

      public string Value { get; set; }

      public bool IsDeleted { get; set; }

   }


    public class SystemController : BaseController
    {

         public ActionResult List()
         {
            var model = new SystemTestModel { 
                          Entities = new List<SystemListEntity>() };

            return View(model);
         }

         [HttpPost]
         public ActionResult List(SystemTestModel model)
         {
            var entities = model.Entities.Where(i => i.IsDeleted == false);

            //Save entities

            //Reload UI
            return View(new SystemTestModel { Entities = entities.ToList() });
         }
}

Kendo MVVM Sample in ASP.NET MVC

Kendo MVVM is exciting in UI application development framework that binds a JavaScript model to an HTML view. At the core of the MVVM framework is a JavaScript model definition that defines members of the view model that the view will use. For instance, here is a simplified model:

var vm = kendo.observable({ Name: "" });

The idea here is that the model has a Name property that will be bound. The kendo.observable call wraps the model and prepares it for two-way binding in the UI. In our example, this property can be bound to a control like:

<input type="text" name="Name" data-bind="value:Name" />

Our name property in our view model is bound to the textbox, and the data-bind attribute is responsible for wiring everything up. When the textbox value changes, the view model is updated, and vice versa. This is the main benefit of two-way binding. Taking this and looking at a more complicated example, we can use the same approach within ASP.NET MVC. Below is a sample complex example:

var viewModel = kendo.observable({

                     ID: null,
                     ParentItemCategoryTypeID: null,
                     Code: null,
                     Name: null,
                     IsActive: null,
                     Sequence: null,

                     categoriesDataSource: new kendo.data.DataSource({
                           data: @(Html.Raw(JsonConvert.SerializeObject(Model.ItemCategories)))
                     }),

                     onClear: function (e) {
                           this.set("ID", null);
                           this.set("ParentItemCategoryTypeID", null);
                           this.set("Code", null);
                           this.set("Name", null);
                           this.set("IsActive", false);
                           this.set("Sequence", null);
                     },
.
.
});

This view model has 6 properties (ID, Code, Name, etc.); it also has one complex property (a kendo data source that is used to bind to a grid) and an event handler. I’ll come back to the kendo data source later.

At this point, the init method copies the values from the view model (defaulted to null) to input and other HTML elements in the view. In order to link an element to the view model, it requires the data-bind attribute, like the following samples:

<input type="text" class="form-control" data-bind="value:Name" />

Since MVC HTML helpers render out textboxes, we can use TextBox for with the data_ notation. The data_bind attribute renders as data-bind, so we have complete data- attribute support.

@Html.TextBoxFor(i => i.Name, new { @class = "form-control", data_bind = "value:Name" )

Other uses of data-bind attribute can be to wire up click event handlers, bind listviews to kendo data sources, control the visibility of an HTML element, and more.

<button id="ClearFormButton" type="reset" class="btn btn-warning" data-bind="click: onClear">Clear</button>

<tbody id="listview" data-role="listview" data-template="ListItemTemplate" data-selectable="true" data-bind="source:categoriesDataSource, events:{change:onListChange}">

<div data-bind=”visible:showSection”>

The “click” and “events” binding wire up an event handler to a function in the view model, which handles the event. In the event handler, the this pointer refers to the view model, also providing an event argument that gives you access to the underlying control as well. There are many types of other bindings, such as “css”, “visible”, etc. On init, the values from the view model are wired up to each control, and any change within the input control also updates the view model back. The view model has a get/set method to retrieve and use, or update, the view model.

Notice how data-bind for the listview is categoriesDataSource; this is a kendo.data.DataSource object defined on the viewmodel. Interestingly enough, this object takes a URL to a web service or JSON/JavaScript objects. Using Json.NET, the code above (duplicated below) serializes an array into a JavaScript, the following DataSource definition:

categoriesDataSource: new kendo.data.DataSource({
                data: @(Html.Raw(JsonConvert.SerializeObject(Model.ItemCategories)))
        }),

Is rendered as the following:

categoriesDataSource: new kendo.data.DataSource({
                data: [{"ID": 1, "Name": "ABC", ...}]
        }),

What ties the view to the model is the kendo.init method:

kendo.init("body", viewModel);

Now our view is bound to our model, and everything is initialized appropriately.

Adding Security To Html Helpers

I know the new MVC 5 HTML tag attributes for rendering ASP.NET widgets is all the rage, but there are a lot of useful approaches to using the server-side HTML helpers.  One simple extension method we are going to look at is adding control level security.  Often within our applications, we have a means of providing UI security at the control level.  We may, for instance, hide a control if the user doesn’t belong to a certain role.  It’s really simple to add this as an extension to IHtmlString, which is what HTML tag helpers do.  First, let’s look at how this might be used:

@Html.TextBoxFor(i => i.AccountID).IfInRole("ADMIN")

Notice how our textbox has an IsVisible method; this checks if the user is in the ADMIN role, and if so, it does the following:

public static IHtmlString IfInRole(this IHtmlString html, string role)
{
    if (HttpContext.Current == null)
       return html;

    if (HttpContext.Current.User.IsInRole(role);
       return html;
    else
       return new MvcHtmlString("");
}

In this method, if the user doesn’t have permissions, it outputs a blank string instead of the original HTML, thus providing some level of control security. We could use claims to do this, or some other security feature; it really doesn’t matter what is used behind the scenes. Also, we could also provide some default template to use if the control is hidden, as a blank space may not be optimal. This can especially be the case if you are using Twitter Bootstrap, because your form may look like:

Account @Html.TextBoxFor(i => i.AccountID, new { @class = "form-control" })

And thus a wrapper around it like:

@if (Html.IsInRole("Admin")) {
  
..
}

Or using a lambda template might be better. When there is supporting HTML wrapping the HTML Helper, showing or hiding may be a little more complicated depending on your design. I hope you see from this simple example how you can add some security features into your application using the old-school HTML helpers.