Posts tagged asp.net mvc

Creating a custom ValueType and Serialising with a custom JsonResult

When trying to serialise your model into Json you would notice the ugly way that the Microsoft JavaScriptserializer outputs dates. ie. {”d”:”\/Date(1240718400000)\/”}

This might not be a problem when you are using JQuery or Javascript, but what if your consumer is, say, an IPhone or another device? Wouldn’t you rather stick to a platform independent and recognised format?

The steps below might be a bit too drastic for your implementations, but follow them and you might also learn how to create your own ValueType and CustomJsonSerialiser all in one go!

This is what we want to accomplish. We only needed to give one converter to our CustomConverterJsonResult, but you could make this a list or even a configuration/ioc injection.

 public ActionResult Index(int? id)
 {
      return new CustomConverterJsonResult (new UnixDateTimeConverter(), _repository.GetPerson(id));
 }

Below is our custom ValueType. This allows you to do the following:

UnixDateTime uDateTime = DateTime.Now;
//OR
DateTime dateTime = uDateTime;
//OR > < => and even casting between them
public struct UnixDateTime : IComparable
{
    private static DateTime _baseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
    private readonly long _epochSeconds;

    public UnixDateTime(DateTime dateTime)
    {
       _epochSeconds = ConvertToUnixEpochSeconds(dateTime) ?? 0;
    }

    public UnixDateTime(long epochSeconds)
    {
       _epochSeconds = epochSeconds;
    }

    public override bool Equals(object obj)
    {
       if (!obj.GetType().IsAssignableFrom(typeof(UnixDateTime)))
          return false;
       return ((UnixDateTime)obj)._epochSeconds.Equals(_epochSeconds);
    }

    public bool Equals(UnixDateTime other)
    {
       return other._epochSeconds.Equals(_epochSeconds);
    }

    public override int GetHashCode()
    {
       return _epochSeconds.GetHashCode();
    }

    public int CompareTo(object obj)
    {
       return _epochSeconds.CompareTo(((UnixDateTime) obj)._epochSeconds);
    }

    public override string ToString()
    {
       return _epochSeconds.ToString();
    }

    public static bool operator >(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds > target._epochSeconds;
    }

    public static bool operator <(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds < target._epochSeconds;
    }

    public static bool operator ==(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds == target._epochSeconds;
    }

    public static bool operator !=(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds != target._epochSeconds;
    }

    public static implicit operator UnixDateTime(DateTime dateTime)
    {
       return new UnixDateTime(dateTime);
    }

    public static implicit operator UnixDateTime(long value)
    {
       return new UnixDateTime(value);
    }

    public DateTime? ToDateTime()
    {
       return ConvertFromUnixEpochSeconds(_epochSeconds);
    }

    private static long? ConvertToUnixEpochSeconds(DateTime? date)
    {
       if (!date.HasValue)
          return null;

       return (long)((DateTime)date - _baseDateTime).TotalSeconds;
    }

    private static DateTime? ConvertFromUnixEpochSeconds(long? seconds)
    {
       if (!seconds.HasValue)
          return null;

       return _baseDateTime.AddSeconds(seconds.Value);
    }
}

We then need a CustomConverterJsonResult. The reason for this is to inject the converters needed (no support for this in the normal JsonResult).

public class CustomConverterJsonResult : JsonResult
{
    private readonly JavaScriptConverter _customConverter;

    public CustomConverterJsonResult(JavaScriptConverter customConverter, object data)
    {
       _customConverter = customConverter;
       Data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
       if (context == null)
          throw new ArgumentNullException("context");

       HttpResponseBase response = context.HttpContext.Response;

       response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

       if (ContentEncoding != null)
          response.ContentEncoding = ContentEncoding;

       if (Data != null)
       {
          JavaScriptSerializer serializer = CreateJsonSerializer();
          response.Write(serializer.Serialize(Data));
       }
    }

    private JavaScriptSerializer CreateJsonSerializer()
    {
       var serializer = new JavaScriptSerializer();
       serializer.RegisterConverters(new []{_customConverter});
       return serializer;
    }
}

And finally… the JavascriptConverter.

   public class UnixDateTimeConverter : JavaScriptConverter
   {
       public override object Deserialize(IDictionary<string, object> dictionary, Type type,    JavaScriptSerializer serializer)
       {
          if(dictionary != null)
          {
             var stringValue = string.Empty + dictionary["UnixEpochSeconds"];
             if(string.IsNullOrEmpty(stringValue))
                return null;

             return new UnixDateTime(long.Parse(stringValue));
          }

          return null;
       }

       public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
       {
          var result = new Dictionary<string, object> { { "UnixEpochSeconds", obj.ToString() } };
          return result;
       }

       public override IEnumerable<Type> SupportedTypes
       {
          get { return new ReadOnlyCollection<Type>(new List<Type>(new[] {     typeof(UnixDateTime), typeof(UnixDateTime?) })); }
       }
}

This creates the following output:

{"Person":[{"Name":"John Doe","LastUpdated":[{"UnixEpochSeconds":"187653000"}]]}

NBouncer, my Context Aware Validation Framework

For most people out there using the current Validation Frameworks (DataAnnotations, Nhibernate Validation) are more than enough. But for some, like me, I need mine to be “Context Aware”.

What do I mean with “Context Aware”? Well lets say, for instance, that you are phoning your bank for an insurance policy. The first thing they need is to obtain just enough info to get you in their database so that they can take the application further. Once they have you, then they forward the application where underwriting, risk calculation etc can take place. So the application goes through quite a few states. We could say it has a preliminary, draft, final etc… state at each given moment. The validation and business rules might be completely different depending on what state the agreement is in.

Three more requirements had to be satisfied before I started to plan a prototype.

1. Needs to be VERY simple to use
2. Needs to stay out of my POCO objects (no attributes!)
3. Validation rules are just a subset of business rules. I want to be able to use the validation framework for complex business rules and simple validation and treat them as one layer.

After a few days NBouncer was born. This is just a prototype and more feedback is needed to justify investing more time into. I know there are “Context Aware” rule frameworks out there, but I need mine to be VERY SIMPLE.

Enough rambling, lets see some code!

Lets say we have a Person object, an Agreement object and a Hobby object: (note how clean these are, this is how they will stay!)

public class Person
{
	public string Name { get; set; }
	public int Age { get; set; }
	public IList<Hobby> Hobbies = new List<Hobby>();
}

public class Agreement
{
	public AgreementState State { get; set; }
}

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

The first example is to send a Warning message if the execution action is “Validate”, but to send an Error if the user is trying to “Persist” the person. The only thing we need to do is create a PersonRules class and set an attribute specifying it’s a “RuleProvider” for the “Person” class…

[RuleProviderFor(typeof (Person))]
public class PersonRules : RuleProvider<Person>
{
	public PersonRules(RuleContext context)
		: base(context)
	{
	}

	protected override void RegisterRules()
	{
		CreateNameValidationRules();
	}

	private void CreateNameValidationRules()
	{
		switch (Context.ExecutionAction)
		{
			case ExecutionAction.Validate:
				RegisterRule(x => string.IsNullOrEmpty(x.Name),
							 CreateWarning(ErrorMessages.NameRequired, "Name"));
				break;
			case ExecutionAction.Persist:
				RegisterRule(x => string.IsNullOrEmpty(x.Name),
							 CreateError(ErrorMessages.NameRequired, "Name"));
				break;
		}
	}
}

A more complicated example is when we have custom “Actions” and the rules are dependent of other classes…

[RuleProviderFor(typeof (Person))]
public class PersonRules : RuleProvider<Person>
{
	public PersonRules(RuleContext context)
		: base(context)
	{
	}

	protected override void RegisterRules()
	{
		var data = Context.ResolveData<Agreement>();
		CreateNameValidationRules();
		CreateAgeValidationRules(data);
		CreateHobbyValidationRules(data);
	}

	private void CreateHobbyValidationRules(Agreement agreement)
	{
            if (Context.CustomAction == CustomActions.UnexpectedExit)
	        {
		      RegisterRule(x => x.Hobbies.Count == 0,
                       CreateError(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
            }
            else
            {
                switch (Context.ExecutionAction)
                {
                    case ExecutionAction.Persist:
                        if (agreement.State == AgreementState.Draft)
                        {
                            RegisterRule(x => x.Hobbies.Count == 0,
                                         CreateWarning(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
                        }
                        else if(agreement.State == AgreementState.Final)
                        {
                            RegisterRule(x => x.Hobbies.Count == 0,
                                         CreateError(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
                        }
                        break;
                    case ExecutionAction.Release:
                        RegisterRule(x => x.Hobbies.Count == 0,
                                     CreateError(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
                        break;
                }
            }
        }

        private void CreateAgeValidationRules(Agreement agreement)
        {
            switch (Context.ExecutionAction)
            {
                case ExecutionAction.Persist:
                    if (agreement.State == AgreementState.Draft)
                    {
                        RegisterRule(x => x.Age < 18,
                               CreateWarning(ErrorMessages.AgeCannotBeLessThan18, "Age"));
                    }
                    else if(agreement.State == AgreementState.Final)
                    {
                        RegisterRule(x => x.Age < 18,
                               CreateError(ErrorMessages.AgeCannotBeLessThan18, "Age"));
                    }
                break;
                case ExecuteAction.Validate:
                        RegisterRule(x => x.Age < 18,
                               CreateWarning(ErrorMessages.AgeCannotBeLessThan18, "Age"));
                break;
            }
        }
    }

The only thing left to do is to see how we validate…

public ActionResult EditPerson(Person person)
{
    var agreement = new Agreement {State = AgreementState.Draft};
    var ruleContext = new RuleContext(ExecutionAction.Persist);
    ruleContext.RegisterData(agreement);

    var rules = person.GetRuleProvider(ruleContext);
    if(rules.Validate())
    {
       rules.ValidationResult.ForEach(x => ModelState.AddModelError(x.Message, x.TargetProperty);
       return View(person);
    }
    Service.CreateAgreement(person, agreement);
    return View(person);
}

As I said before, this is just a prototype and feedback would be appreciated!

Writing Facebook Apps with ASP.NET MVC, Silverlight, LINQ2Facebook and BDD

This weekend I looked into creating facebook applications from a .NET perspective. It turns out a quick search presents loads of support starting with the Facebook Developer Toolkit (Update: Just heard version 3 was released yesterday which gives silverlight and mvc support, wow what a coincidence?) and LINQ2Facebook (Fql).

I decided to do some research and ended up created a Facebook application framework using ASP.NET MVC, Silverlight, LINQ2Facebook. I also used StoryQ to POC their BDD framework and give the community a chance to see its power.

I have created a codeplex project with the source code here:

Facebook MVC BDD Silverlight Framework

Source code sample:

public ActionResult Index()
{
	if (_service.TryAuthenticating())
	{
		user user = _service.GetCurrentUser();
		var silverlightViewModel = new SilverlightViewModel
									   {
										   ApplicatonName = "TestApp",
										   Width = "400",
										   Height = "400"
									   };

		silverlightViewModel.Params.Add("Name", user.name);
		silverlightViewModel.Params.Add("Picture", user.pic_big);

		return View(silverlightViewModel);
	}
	throw new AuthenticationException("Not allowed!");
}
[Test]
public void IndexActionShouldReturnViewModelWithCurrentLoggedInUser()
{
    var story = new Story("Index action should return a new silverlight view model");

    story.AsA("facebook application home page")
        .IWant("to receive a new silverlight view model")
        .SoThat("I can send it to the silverlight applicatioin")
        .WithScenario("Get silverlight view model")
        .Given(() => Steps.TheUserIsLoggedInWithUsername("Joe Blogs"))
        .When(() => Steps.TheUserEntersTheHomePage())
        .Then(() => Steps.EnsureTheCurrentLoggedInUserDetailsIsReceivedInTheViewModel());

    story.Assert();
}

producing output:

Story: Index action should return a new silverlight view model

As a facebook application home page
I want to receive a new silverlight view model
So that I can send it to the silverlight applicatioin

Scenario 1: Get silverlight view model
Given The user is logged in with username (Joe Blogs) Passed
When The user enters the home page Passed
Then Ensure the current logged in user details is received in the view model Passed

ASP.NET MVC JQuery ScriptManager

As I was developing a CMS system for a client, we had a very unique scenario (well maybe not that unique) where we had custom “parts” which you could add to a page. The “parts” were highly customisable, thus you could have 3 instances of the same “part” on one page. The html and javascript rendered by the part would conflict with each other, because they had the same id’s and registered events.

I needed something similar to the old ASP.NET Script manager and the way that old ASP.NET used the “clientId” instead of the “htmlId” when dealing with html objects. The “clientId” was a generated unique key that prevented duplicated user controls conflicting with one another.

I found quite a few implementations of ScriptManager (http://pietschsoft.com/post/2009/08/13/Simple-ScriptManager-for-ASPNET-MVC.aspx, http://aspmvccombine.codeplex.com/) for MVC, but none of them were solving my unique “htmlId” problem. If you are looking for a ScriptManager for MVC, then the two solutions I provided would be more than enough. If, however, you are in a similar situation as I am with the html controls, please read on…

I decided to combine knowledge obtained from the two ScriptManager implementations, and create my own light-weight solution addressing both problems.
Because I wanted the usage of this to be very simple, I created a fluent interface which I can use in all my parts…

This is what the end result looks like:

<% Html.ScriptManager()
     .CreateClientScript(GetUniqueId())
       .AddParam("SelectId", GetUniqueId("selectList"))
       .AddParam("SourceUrl", Url.Action("Index", "Person"))
       .Ready(() => {%>
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
      <%});%>

<% Html.ScriptManager().AddStaticMethod("populate_combobox", () =>{ %>
    jQuery.populate_combobox = function(data, selectId) {
        $.each(data, function() {
            var option = new Option(this.text, this.value);
            var dropdownList = $(selectId)[0];
            if ($.browser.msie) {
                dropdownList.add(option);
            } else {
                dropdownList.add(option, null);
            }
        });
    }
<%});%>

<div id="<%=GetUniqueId() %>_part">
 <select id="<%=GetUniqueId("selectList") %>"></select>
</div>

My “GetUniqueId()” function returns a combination of the PartId, PageId, but you can replace this with anything you fancy.
The javascript that gets generated by this is:

var ContentPart_AboutPage_82 = {
        Init: function(params) {
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
        }
}
var ContentPart_AboutPage_83 = {
        Init: function(params) {
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
       }
}
var ContentPart_AboutPage_84 = {
        Init: function(params) {
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
       }
}
$(document).ready(function() {
    ContentPart_AboutPage_82.Init({
       SelectId:'ContentPart_AboutPage_82_selectList',
       SourceUrl:'/Person'
    });
    ContentPart_AboutPage_83.Init({
       SelectId:'ContentPart_AboutPage_83_selectList',
       SourceUrl:'/Person'
    });
    ContentPart_AboutPage_84.Init({
       SelectId:'ContentPart_AboutPage_84_selectList',
       SourceUrl:'/Person'
    });
});

    jQuery.populate_combobox = function(data, selectId) {
        $.each(data, function() {
        var option = new Option(this.text, this.value);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
      });
    }

Update: I have gone even further and added the concept of “SharedVariables” to the ScriptManager where the “SourceUrl” above and even the Json request is fired only once!

Here is my ScriptManager Class:

public class ScriptManager
{
    private readonly HtmlHelper _helper;

    public IDictionary<string, ClientScript> ClientScripts
    {
       get
       {
          if (_helper.ViewContext.HttpContext.Items["ClientScripts"] == null)
          _helper.ViewContext.HttpContext.Items["ClientScripts"] = new Dictionary<string, ClientScript>();

          return (IDictionary<string, ClientScript>)_helper.ViewContext.HttpContext.Items["ClientScripts"];
       }
    }

    public IDictionary<string, Action> Methods
    {
      get
      {
         if (_helper.ViewContext.HttpContext.Items["ScriptMethods"] == null)
         _helper.ViewContext.HttpContext.Items["ScriptMethods"] = new Dictionary<string, Action>();

         return (IDictionary<string, Action>) _helper.ViewContext.HttpContext.Items["ScriptMethods"];
      }
    }

   public ScriptManager(HtmlHelper helper)
   {
       _helper = helper;
   }

   public ClientScript CreateClientScript(string key)
   {
      if(!ClientScripts.ContainsKey(key))
       ClientScripts.Add(key, new ClientScript());

      return ClientScripts[key];
   }

   public ScriptManager AddStaticMethod(string key, Action javascript)
   {
     if(!Methods.ContainsKey(key))
       Methods.Add(key, javascript);

     return this;
   }

   public void Render()
   {
     TextWriter writer = _helper.ViewContext.HttpContext.Response.Output;
     writer.WriteLine("<script type=\"text/javascript\">");

     foreach (var clientScript in ClientScripts.Keys)
     {
       writer.WriteLine("var " + clientScript + " = {");
       writer.WriteLine("        Init: function(params) {");
       ClientScripts[clientScript].Value();
       writer.WriteLine("        }");
       writer.WriteLine("}");
     }

     writer.WriteLine("$(document).ready(function() {");
     foreach(var clientScript in ClientScripts.Keys)
     {
       var client = ClientScripts[clientScript];
       writer.WriteLine("    " + clientScript + ".Init({");
       foreach (var param in client.Params)
         writer.WriteLine("       {0}:'{1}'{2}", param.Key, param.Value, IsLast(client.Params, param.Key) ? string.Empty : ",");
         writer.WriteLine("    });");
       }
     writer.WriteLine("});");
     foreach(var method in Methods.Values)
       method();
     writer.WriteLine("</script>");
   }

   private static bool IsLast(IDictionary<string, string> parameters, string key)
   {
     var keys = parameters.Keys.ToList();
     return keys.Count > 0 && keys[keys.Count-1] == key;
   }
}

Here is the ClientScript class:

public class ClientScript
{
   private readonly IDictionary<string, string> _parameters = new Dictionary<string, string>();
   private Action _script;

   public IDictionary<string, string> Params
   {
     get { return _parameters; }
   }

   public ClientScript AddParam(string key, string value)
   {
     Params.Add(key, value);
     return this;
   }

   public ClientScript Ready(Action script)
   {
     _script = script;
     return this;
   }

   public Action Value
   {
     get
     {
       return _script;
     }
   }
}

Here is my extension method:

public static ScriptManager ScriptManager(this HtmlHelper helper)
{
    return new ScriptManager(helper);
}

And then you only need to add this at the end of your master page:

<% Html.ScriptManager().Render(); %>

Yes/No Dropdownlist Extension for ASP.NET MVC

I am not a big fan of using checkboxes for a simple yes/no question on a form. I use checkboxes only for selecting multiple items to perform an action on, or when I am using a checkboxlist. The reason for this is because I believe a yes/no question has three possible states, not only two.

If you are asking a user “Do you agree with our terms?”, the general consensus is to assume that not clicking the box is “forgetting” to make a selection and warning me that “You have forgotten to tick our terms and conditions”. In this situation the case may be so, but what if I did not agree? What if the question was “Do you want to opt out of us sending you loads and loads of spam?” and simply not spotting this question.

I believe that if you did not make a selection it is a valid state. Thus a yes/no question, in my opinion, has the following states; “yes”, “no” and “did not choose”.
Once again, I don’t simply rant, I also offer a solution… a very simple extension method which I love using for all my yes/no questions instead of checkboxes. In this case I made the “not selected” state 0.

public static string YesNoDropDownList(this HtmlHelper helper, string id, string selectedValue)
        {

            var list = new SelectList(new[]
                              {
                                  new {text = "Select", value = "0"},
                                  new {text = "No", value = "1"},
                                  new {text = "Yes", value = "2"}
                              }, "value", "text", selectedValue);

            return helper.DropDownList(id, list);
        }

PS: It also looks a bit neater and more uniform.

Update Form Fields with JSON result in ASP.NET MVC

Wouldn’t it be nifty to receive a JSON result object from AJAX and it automagically updates your form fields? Those who said “No” leave now!
I had to find a way to iterate through my JSON properties and, if I named the fields the same as the JSON properties, update them all in one go.

Lets use a simple “Person” model and have a look at the ASP.NET MVC action:

public ActionResult GetPerson(int id)
{
    var person = Context.GetPerson(id);
    return Json(new
                    {
                        success = true,
                        model = new
                                    {
                                        person.Id,
                                        person.Name,
                                        person.Surname,
                                        person.Age,

                                    }
                    });
}

As you can see this returns a DTO (data transfer object) as JSON result and is ready to be consumed via AJAX…

$.getJSON("/Person/1", function(data) {
    if (data.success) {
        $.updateForm(data.model);
    } else {
        alert("An error occurred");
    }
});

All we then need is the magical “$.updateForm” method that contains all the voodoo:

jQuery.updateForm = function(model) {
   // we iterate through all the properties
   for (var property in model) {
        // evaluate the expression to get the value
        var propertyValue = eval("model." + property);
        // and update the field
        $("#" + property).val(propertyValue);
    }
};

Currenty this will work fine for textboxes and textareas as this was all the functionality I needed for now. If anyone extends this for “select”, “checkbox”, “radiobutton” etc… please share with us so I can update this post.

Kaboom! – JQuery MVVM Framework for the web

Screenshot“Kaboom!” is one of those things you stumble upon and intrigues you from the start. It probably needs more work (not to mention documentation), but certainly gives you a peak at what I believe could be the next big thing in the ASP.NET MVC world. Having just finished a CMS system where I used a very rich JQuery client, I found this a very probable next step. Already using “jquery.forms” to submit all my forms via ajax POST and using “$.getJSON” for all my GET actions, my views started to get pretty lean. I thought, what if I had a JQuery ViewModel that would handle my UI commands and handle all my communication with my controller? A quick search lead me to “Kaboom!”.

The first thing I worried about was testability. “QUnit” (http://docs.jquery.com/QUnit) seems to be a very powerful testing framework that would probably give me more coverage than what I had before! UnitTesting – Check :)

So lets look at one of the samples in the codeplex download, specifically the Asp.Net MVC sample…

We start with a “Person” Model:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And a “PersonController” class which has a Search action:

public class PersonsController : Controller
{
    public JsonResult Search(string searchString)
    {
        List persons = new List();
        persons.Add(new Person { FirstName = "Kozin", LastName = "Osot" });
        persons.Add(new Person { FirstName = "Setesyci", LastName = "Rynaugh" });
        persons.Add(new Person { FirstName = "Atheck", LastName = "Garash" });

        return Json(persons
            .Where(p => p.FirstName.ToLower().Contains(searchString.ToLower()) ||
                p.LastName.ToLower().Contains(searchString.ToLower())).ToList());
    }
}

Then we create a “SearchViewModel” js file and put this in our “ViewModels” folder like so:

var SearchViewModel = {
    Initialize: function(args, callback) {
        Kaboom.register("Search", SearchViewModel.Search);
        SearchViewModel.SearchResults = new Array();
        callback();
    },

    Ready: function() {
        SearchViewModel.Search();
    },

    SearchString: '',
    SearchResults: null,
    Search: function() {
        $.getJSON('/Person/Search',// You can set this as a hidden field on your View with 'Url.Action(..' and simply do $('#searchSource').val()
            { searchString: SearchViewModel.SearchString },
            SearchViewModel.PopulateSearchResults);
    },

    PopulateSearchResults: function(data) {
        SearchViewModel.SearchResults = data;
        Kaboom.notify(SearchViewModel, "SearchResults");
    }
}

And our “Search” view would hook up to our view model like so…

<head runat="server">
    <title>Search</title>
    <% string version = DateTime.Now.Ticks.ToString(); %>
    <script type="text/javascript" src="../../ViewModels/Persons/SearchViewModel.js?id=<%= version %>"></script>
    <script type="text/javascript" src="Scripts/jquery-1.3.2.js?id=<%= DateTime.Now.Ticks.ToString() %>"></script>
    <script type="text/javascript" src="Scripts/json2.js?id=<%= DateTime.Now.Ticks.ToString() %>"></script>
    <script type="text/javascript" src="Scripts/kaboom.js?id=<%= DateTime.Now.Ticks.ToString() %>"></script>

</head>
<body>
    Quick start shows how to communicate with an aspMVC controller.....<br />
    <input type="hidden" id="viewmodel" viewmodel="SearchViewModel" debug="0" />
    <div id="Debug"></div>
    Search:<br />
    <input type="text" bindto="SearchString" mode="TwoWay" /><br />
    <input type="button" value="Search" command="Search" />
    <br />
    <table bindto="SearchResults">
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Options</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>$FirstName</td>
                <td>$LastName</td>
                <td><a href="#" onclick="alert('$FirstName')">Delete</a></td>
            </tr>
        </tbody>
    </table>
</body>

You can bind all your view actions to commands.

<input type="button" command="Save" value="Bound to Save command via jQuery(element).click()" /><br /><br />
<input type="button" command="Save" trigger="dblclick" value="Bound to Save command via jQuery(element).dblclick()" /><br /><br />
<input type="button" command="Save" trigger="blur" value="Bound to Save command via jQuery(element).blur()" /><br /><br />
<input type="button" command="Save" trigger="customaction" value="Bound to Save command via jQuery(element).customaction()" /><br /><br />

… and it has support for other controls and more complex bindings.

<select bindto="Person.Salutation"
         datatextfield="Name"
         datavaluefield="Id"
         datasourceid="Salutations"
         onbind="ProgrammaticallyBindIt" >
   <option value="0">[select]</option>
</select>

There are loads of other examples, including binding to Tables, Divs, Spans, Checkboxes etc. You can download the framework here.

Changing the target filename of TransmitFile in asp.net mvc

Say a file has a physical filename of ‘xyz.pdf’, but when you send it to the user you want it to have a name like ‘myxyzbrilliantfilename.pdf’. How do you change the target filename when transmitting files through the output stream of Response without it popping up a download dialog?

I have searched wide and wild and the only way you could do this is by modifying the “ContentDisposition” like so:

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// OR
Response.AddHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");

The “attachment” setting opens a dialog to save the file with the correct name and the “inline” setting doesnt open a dialog, but ignores the filename!
This is not the behaviour I am looking for, so I had a quick coffee and came up with the following very simple solution!

My solution came in the form of a new route in my mappings:

routes.MapRoute(
    "ResourceModulePdf", // Route name
    "ResourceModule/Pdf/{id}.pdf", // URL with parameters
    new
    {
        controller = "ResourceModule",
        action = "Pdf",
        id = "",
        sourceFilename = ""
    } // Parameter defaults
    );

and my ‘pdf’ action:

public ActionResult Pdf(string id, string sourceFilename)
{
    // We do not need to do anything with 'id'. It has served it's purpose already
    return new FileResult(sourceFilename, "application/pdf");
}

… and my FileResult

public class FileResult : ActionResult
{
    public String ContentType { get; set; }
    public byte[] ImageBytes { get; set; }
    public String SourceFilename { get; set; }

    //This is used for times where you have a physical location
    public FileResult(String sourceFilename, String contentType)
    {
        SourceFilename = sourceFilename;
        ContentType = contentType;
    }

    //This is used for when you have the actual image in byte form
    //  which is more important for this post.
    public FileResult(byte[] sourceStream, String contentType)
    {
        ImageBytes = sourceStream;
        ContentType = contentType;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.Clear();
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.ContentType = ContentType;

        if (ImageBytes != null)
        {
            var stream = new MemoryStream(ImageBytes);
            stream.WriteTo(response.OutputStream);
            stream.Dispose();
        }
        else
            response.TransmitFile(SourceFilename);
    }
}

All we need to do now is construct our hyperlinks like so:


Doc

By default the “TransmitFile” method will take the name of the filename you used in your hyperlink and the result is exactly what we wanted!

Handling dynamic resources with ASP.NET MVC

A good way to handle your resources in ASP.NET MVC is by storing them in a database. With Microsoft SQL Server 2008 supporting streaming (read more), keeping your resources in the database gives you all of Microsoft SQL Server’s features for free. (ie. querying, profiling, backup, synchronisation and not to mention speed)

In the past we would normally create a HTTP handler to write to the Response.OutputStream, but with ASP.NET MVC we simply need to create another action on our preferred controller…

First we create an ‘ImageResult’ class which will handle our output.

public class ImageResult : ActionResult
{
    public Image Image { get; set; }
    public string ContentType { get; set; }
    public ImageFormat ImageFormat { get; set; }

    public ImageResult(Image image, string contentType, ImageFormat imageFormat)
    {
        Image = image;
        ContentType = contentType;
        ImageFormat = imageFormat;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = ContentType;
        Image.Save(context.HttpContext.Response.OutputStream, ImageFormat);
    }
}

And then we simply create an action for our specific needs:

public ActionResult ResourceImage(string key)
{
    var resourceItem = _provider.GetResourceItem(key);
    var bitMap = new Bitmap(resourceItem.Stream);

    return new ImageResult(bitMap, resourceItem.ContentType, resourceItem.Format);
}

public ActionResult ResourceFile(string key)
{
    var resourceItem = _provider.GetResourceItem(key);
    return File(resourceItem.Stream, resourceItem.Format, key);
}

All you need to do is create your own provider that would find the key in the database and return the stream and the format of the file.

JQuery function to populate a select box

Something you might be repeating while building a user interface is populating a select box with JSON results. Here is a quick demonstration on a very simple way to do this. Put the ‘populateSelect’ method in a global .js file and use it throughout your project as ‘$.populateSelect(args…)’

ASP.NET MVC Action Method

public ActionResult GetUsers()
{
     var data = Service.QueryUsers()
           .Select(x => new {value = x.Id, text = x.Name});

      return Json(data);
}

Usage:

var url = "<%=Url.Action("GetUsers", "UserController") %>";

$.getJSON(url, function(data, textstatus) {
        $.populateSelect("#someSelectBox", data);
});

Global Method:

// JQuery Method
jQuery.populateSelect = function(selectId, data) {
    $.each(data, function() {
        var option = new Option(this.text, this.value);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
    });
};

Removing all Items from a select list is just as simple:

$("#mySelectList")
   .find("option")
   .remove();

And lastly how to Append or Prepend items to the list:

// Add options to the end of a select
$("#mySelectList")
    .append("");

// Add options to the start of a select
$("#mySelectList")
    .prepend("");