RSS

Asp.net MVC JsonResult, Anonymous types and Testing

This article is an explanation on how to access the data from a JsonResult for using it in your unit testing

The JsonResult type has a property called Data of type Object that you can parse if you have used a concrete object as your data for example:

Model

public class Person
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
  }

Controller Action

public JsonResult Index()
{
  //Logic ....
  var person = new Person
                      {
                          Id = 1,
                          Name = "Nadeem",
                          Age = "24"
                      };
  return Json(person);
}

Unit Test

[Test]
public void Testing()
{
  var controller = new HomeController();

  var result = controller.Test();
  var data = result.Data as Person; //you can now access the Person properties

  //Assert
}

This is all good but we get stuck if we want to pass an anonymous object to our JsonResult there is no way to cast to something to access an anonymous object properties

the solution is i made two custom helper methods that we can use to get values from a JsonResult.Data object
ill follow after with an example of using it

The custom helper:

public static class Helper
{
  public static object GetValue(this JsonResult result,string propertyName)
  {
    IDictionary<string, object> wrapper = new System.Web.Routing.RouteValueDictionary(result.Data);
    return wrapper[propertyName];
  }
  public static T GetValue<T>(this JsonResult result, string propertyName)
  {
    return (T) GetValue(result, propertyName);
  }
}

Example:

Controller Action

public JsonResult Index()
{
  //Logic ....
  return Json(new {number = 1});
}

Unit Test

[Test]
public void Testing()
{
  var controller = new HomeController();

  var result = controller.Index();

  Assert.AreEqual(1, result.GetValue<int>("number"));
}

This is how to test a JsonResult using  anonymous types

 

For the fun of it we can make a helper that returns a dynamic type (but its not as efficient as the top solution)

The custom helper:

public static dynamic ToDynamic(this JsonResult jsonResult)
{
  var expandoObject = new ExpandoObject();
  var expandoCollection = (ICollection<KeyValuePair<string, object>>)expandoObject;
  var dataWrapper = new RouteValueDictionary(jsonResult.Data);
  foreach (var kvp in dataWrapper)
  {
    expandoCollection.Add(kvp);
  }
  dynamic eoDynamic = expandoObject;
  return eoDynamic;
}

Unit Test

[Test]
public void Testing()
{
  var controller = new HomeController();

  var result = controller.Index();

  Assert.AreEqual(1, result.ToDynamic().number);
}
 
2 Comments

Posted by on February 11, 2013 in MVC

 

Tags: ,

Knockout view model binding variations to a page

Bind a view model to the whole page

First of lets start with a simple example and how to write a simple view model and bind it to the page

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

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

<h2>Hello, <span data-bind="text: fullName "/>!</h2>

And the Javascript file

var User = function() {
    this.firstName = ko.observable("Nadeem");
    this.lastName = ko.observable("Khedr");
    this.fullName = ko.computed(function () {
      return this.firstName() + " " + this.lastName();
    },this);
};
ko.applyBindings(new User());

This will bind our Javascript view model to the whole html document and every variable in the databind attributes wil refer to a property of this one view model

Bind a view model to a partial part of the page

In the previous example we passed our view model to ko.applyBindings, this method take another parameter, which is the DOM element that we want to attach our view model to, In the next example we will attach two different & not related view models to different parts of our page


<div id="section1">
  First name: <input type="text" data-bind="value: firstName" />

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

  <h2>Hello, <span data-bind="text: fullName "/>!</h2>
</div>
<div id="section2">
First name: <input type="text" data-bind="value: firstName" />

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

<h2>Hello, <span data-bind="text: fullName "/>!</h2>
</div>

And the Javascript for this

var User = function(firstName,lastName) {
    this.firstName = ko.observable(firstName);
    this.lastName = ko.observable(lastName);
    this.fullName = ko.computed(function () {
      return this.firstName() + " " + this.lastName();
    },this);
};
ko.applyBindings(new User("Nadeem","Khedr"), $("#section1").get(0));
ko.applyBindings(new User("Phil","Joe"), $("#section2").get(0));

Bind a view model to the whole page and bind other view models to sections inside the page

In a more advanced scenario what we could want is to bind a view model to the whole page & sort of mini view models to different reusable components inside the page

In the previous example we cant define two html sections inside each other with different view models, they must be distinct, in another word we can’t define a master view model for all the page and a small view model for a part of that page because they will collide

A scenario that we would want exactly that

We want a master view model to our page (Layout)
We want a reusable view model for a sidebar that we could use in multiple pages (Partial View)

To achieve that what we will do is go to the parent of the sidebar and tell it stop binding the page view model to your descendant elements

so what will happen exactly is we will define a view model to the whole page without specifying a DOM element to attach it to, and another view model (maybe in another file) for only the side bar and bind it to it

How to do that without getting errors that the properties in the sidebar doesn’t exists in the application view model

We will put a custom attribute on the sidebar container, the attribute will look like this

<div id="sidebarCont" data-bind="allowBinding: false">

what this will do is tell the current view model attached to the document to stop binding itself to the descendant elements for the sidebarCont

the allowBinding is a custom bindingHandler that we defined and looks like this

ko.bindingHandlers.allowBindings = {
      init: function(elem, valueAccessor) {
      var shouldAllowBindings;
      shouldAllowBindings = ko.utils.unwrapObservable(valueAccessor());
      return {
        controlsDescendantBindings: !shouldAllowBindings
      };
    }
  };

the above code is self explanatory all the magic happens with the controlsDescendantBindings
if you want to read more about bindingHandlers you can check this link

 
Leave a comment

Posted by on January 29, 2013 in Javascript

 

Tags: , ,

How the unobtrusive jQuery validate plugin works internally in Asp.net MVC

this is part of “understanding Asp.net Mvc Unobtrusive Validation” series

  1. How the jQuery validate plugin works internally
  2. Understand the Html generated by the unobtrusive validation in Asp.net MVC
  3. How the unobtrusive jQuery validate plugin works internally in Asp.net MVC

What we will be talking about in this article

Read the rest of this entry »

 
3 Comments

Posted by on August 27, 2012 in Javascript

 

Tags: , , ,

Understand the Html generated by the unobtrusive validation in Asp.net MVC

this is part of “understanding Asp.net Mvc Unobtrusive Validation” series

  1. How the jQuery validate plugin works internally
  2. Understand the Html generated by the unobtrusive validation in Asp.net MVC
  3. How the unobtrusive jQuery validate plugin works internally in Asp.net MVC

What we will be talking about in this article

Read the rest of this entry »

 
2 Comments

Posted by on August 22, 2012 in Javascript

 

Tags: , , ,

How the jQuery validate plugin works internally

There are plenty of articles that target how to write custom rules to the jquery.validate plugin but very few targets how this plugin internally works and that’s what we will discuss in this article

this is part of “understanding Asp.net Mvc Unobtrusive Validation” series

  1. How the jQuery validate plugin works internally
  2. Understand the Html generated by the unobtrusive validation in Asp.net MVC
  3. How the unobtrusive jQuery validate plugin works internally in Asp.net MVC

What we will be talking about in this article

Read the rest of this entry »

 
1 Comment

Posted by on August 12, 2012 in Javascript

 

Tags: , , ,

 
Follow

Get every new post delivered to your Inbox.