MVC Guidelines

08.03.10

We have used ASP.NET MVC on a couple of large scale projects and found some guidelines and other resources that we thought were worth sharing. We have compiled a Word document to start with. The document will only grow more in size over time as we add more items that we come across.

Please bookmark this link and follow our Twitter feed on @hypertrends for updates! Meanwhile, here is the download.

HyperTrends-MVC_Framework_Guidelines

Why I now use SimpleModal for all modal popups

3

06.05.10

Eric Martin’s SimpleModal is really the best modal popup utility out there.

I originally started off with jqModal and had numerous issues with it as I started implementing more complex scenarios. The issues primarily have to deal with the fact that I actually have to register a container as a modal container. I consider this as a pull-type of programming. This usually results in issues esp. when you refresh the container div using AJAX. You now have to re-register the jqModal or it will not show modal popups anymore. That coupled with a couple of unique scenarios in some projects led me to think that jqModal while very powerful didn’t suit my needs.
read more »

A better way to pass Action Parameters using jQuery

05.04.10

I have found myself doing very interesting things with jQuery lately. I am pretty amazed by the power it has.
I noticed I was doing stuff pretty half-a**ed using jQuery when it came to passing arguments to controller action methods.
Here is what I was doing:

$.get('/Facilities/Profile/EditStep2?profileId='
+ <%= Model.FacilityProfile.customerProfileId %> + '&item='
+ test

read more »

jqModal with ASP.NET MVC

7

04.28.10

This is going to be a fairly long post explaining the various features of jqModal and how it integrates with ASP.NET MVC. jqModal is a fairly robust, lightweight library that allows easy integration of modal popups with your web-apps. You can download jqModal from HERE

In this example, we demonstrate how jqModal can be used on an MVC page to show a form that allows the user to add a line item to a given order. The scenario is as follows:
1. The user clicks on a hyperlink “Add Line Item”.
2. jqModal opens up and loads the partial view containing the add line item form at runtime.
3. User enters items in the form and then hits “Save”. The modal form uses ajax and inserts the line item into the DB and displays a message to the user.
4. User clicks on Close to close the modal popup.
5. The main page uses ajax and reloads the line items.

This is a fairly common scenario in most web applications.

Without further ado, let’s dive into the code.

Let’s place a simple “Add a Line Item” link on the page. This link is solely responsible for opening the jqModal. As such this link should be decorated with the ‘jqModal’ css class.

<a href="#" class="jqModal">Add a Line Item</a>

The next step would be do add the container DIV that will be used to show the modal dialog. This can be easily set using the code as shown:

<div id="addLineItemControlSection" class="jqmWindow">
</div>

It is important to note that a css-class of ‘jqmWindow’ needs to be associated with the div that will be displayed in the modal popup.

Now, the jqModal site clearly states that we need to initialize the jqModal setup ONLY ONCE when the page loads. Any setups there-after will be considered as updates. To wire up the page to trigger the dialog box when the link “Add a Line Item” is clicked, we initialize jqmodal using the following:

$().ready(function() {
   $('#addLineItemControlSection').jqm({ modal: true,
      ajax: '<%= Url.Action(ActionNames.Add,
 ControllerNames.Detail, new { invoiceId = Model.Invoice.InvoiceId }) %>',
      onHide: myAddClose
   });
});

The above code does a couple of interesting things. On the ‘ready’ event, it wires up the jqModal with the ‘#addLineItemControlSection’ (which is the DIV that will load as modal popup).

The modal: true property indicates that the window will be opened as a modal window and will not be closed until “Close” is explicitly clicked.

The ajax property also allows me to pass the Action method that will be used to display the modal popup. We use an AJAX call to build the modal popup.

The onHide property allows me to fire a javascript after the modal popup is closed. Typically you can use this in scenarios where you want to update the parent window after the child modal popup is closed. In our case, I use this onHide to update the container div containing the line items so that it displays the newly added line item.

As you can see in the controller code below, my modal popup just displays a “partial view” that I return from the controller when I call the Action “Add”.

public ActionResult Add(int invoiceId)
{
      AddInvoiceLineItemViewModel model = new AddInvoiceLineItemViewModel();
      model.LineItems = invoiceLogicInstance.GetLineItemsByInvoiceId(invoiceId);
      model.InvoiceId = invoiceId;
      model.CurrentInvoiceItem = new InvoiceItem();
      return View(ViewNames.InvoiceLineItemControl, model);
}

I return a View called InvoiceLineItemControl which is a partial view and is declared as follows:

As you can see, I am using Ajax.BeginForm to save my line item to the database. On a successful insert, I actually replace the entire lineItemSaveDiv and replace it with new HTML.

Notice that the close link (as decorated by “jqmClose”) line is kept outside the lineItemSaveDiv. This is because after the save is done, I don’t want the link to disappear once I update the result on the modal popup. This will allow me to close the modal window.

In any case, your modal dialog should have the following code, allowing the window to be closed.

<a href="#" class="jqmClose">Close</a>

Once the window is closed, the function set in the onHide property will be called. Here’s the code to update the parent window:

function myAddClose(hash) {
$('#lineItemLoadingDiv').show();
var test = Math.floor(Math.random()*101);
$.get('/Invoicing/Detail/ShowLineItems?invoiceId=' + <%= Model.Invoice.InvoiceId
%> + '&item=' + test, null,
function(data) {
 $('#invoiceItemsDiv').html(data);
});
hash.w.fadeOut('1000', function() { hash.o.remove(); });
}

A couple of important things to note here:

1. I am creating a random number and passing that as an action argument to my controller. Why? This is to make the get request unique each time so that IE doesn’t cache the request and bypass the GET calls. To read more about this, please read my post on IE and the JSON Caching Issue

2. I am calling hash.w.fadeOut. What is that? hash.w is nothing but a way to access the jqmodal window. All I am doing is fading the window out and removing the overlay (by accessing hash.o).
More explanation as obtained from jqmodal site is shown here:

Callbacks allow advanced customization of jqModal dialogs. Each callback is passed the “hash” object consisting of the following properties;

* w: (jQuery object) The dialog element
* c: (object) The config object (dialog’s parameters)
* o: (jQuery object) The overlay
* t: (DOM object) The triggering element

Here are some snapshots:
The modal popup containing the ajax generated form:

After Save is hit, the following confirmation is displayed using ajax:

Hopefully that helped. Feel free to put any comments/suggestions!

MVC Tip: Form submit using HyperLink

1

04.02.10

A lot of times in your MVC forms, you will see the need to submit a form by clicking a hyperlink.
This can be simply done using the following:

<a id="linkSearch" href="javascript:void(0);">Post Me</a>

And then in the document.ready event on the page, we can associate the form submit event as follows:

$('#linkSearch').click(function() {
      $(this).parents('form').submit();
 });

That’s all there is to it!

Facebook style AutoComplete using ASP.NET MVC and FCBKComplete

03.11.10

Many times you will see the need to implement a Facebook style autocomplete textbox. Auto-complete functionality is great because it allows the end user to easily make selection(s) for a given data field.

We had a scenario where we wanted the user to enter multiple states that he is interested in. Of course, FCBKComplete is the best open source plugin for Facebook style auto-completion.

This post should give you a quick idea on how to configure the auto-complete item.

The control can simply be created using the following lines of code:

<select id="stateSelection" name="stateSelection[]">

The state selection control can be setup using FCBKComplete setup scripts as follows:

$("#stateSelection").fcbkcomplete({
json_url: '<%=Url.Action("GetStates", "Profile") %>',
cache: false,
json_cache: false,
filter_case: false,
filter_hide: false,
firstselected: false,
filter_selected: true,
maxitems: 3,
complete_text: "Enter States..."
});

The auto-complete can be simply done by creating a Controller action that returns the JSON result as shown:

public JsonResult GetStates(string tag)
{
    JsonResult result = new JsonResult();

    List tags = TypeDataServiceInstance.SearchStates(tag);
    if (tags != null)
    {
          var data = from r in tags
                         select new
                         {
                            caption = r.Name.Trim(),
                            value = r.StateProvinceId.ToString()
                         };
           result = Json(data);
           result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

   return result;
}

When the form postback occurs, the user can then save the data over to the database. However, this is a little strange because the FCBKControl requires you to name the control as controlname[]. This is an issue because we cannot possibly use this as a Controller parameter since we can’t name arguments ending with [] as parameter names. For this, there is a small hack that you have to apply. The Request.Form object comes in handy for situations like these.

if (Request.Form["stateSelection[]"] != null)
{
        stateIds = Request.Form["stateSelection[]"].ToString();
}

This retrieves the state id’s as a CSV list.

Alternatively, you could also use a Action Filter. To read more about how you could use an action filter, read Haack’s post here.

In the EDIT mode the user can view previously selected states, optionally add more, and also remove existing selections from the list.
FCBKComplete provides us with a nifty little trigger called “AddItem” that allows you to manually add items to the textbox. This aids in displaying pre-selected values.

In order to pre-populate the FCBKComplete, the following method can be used:

function loadStateData() {
$.getJSON('<%= Url.Action("GetSelectedStates", "Profile") %>',
{ currentTime : '<%= DateTime.Now %>' }, function(data) {
for (var i = 0; i < data.length; i++) {
$("#stateSelection").trigger("addItem", data[i]);
}
});
}

Of course, there is the whole issue of JSON Caching on IE which needs to be addressed. This was simply handled by passing in the current date time as a parameter to the JSON action call which makes the browser make a brand new request. To read more about the Controller action implementation, see this previous post of mine.

The rest is simple. On the form postback, obtain the CSV field, parse it out and then call your Service and repository classes to save the data to the database.

Hopefully this helps some folks out there. It took me a while to gather all the documentation from different sites, blogs and comments until I finally got this right.

Rock on Developers! Rock on!

IE JSON Caching Issue

6

I don’t really know if I should call this as a bug. There are two different schools of thought on this issue. One school of thought says, “You gotta do what all the other browsers are doing.” while the other says, “HTTP specification states that GET requests can be cached”

This puts us developers in a perplexing situation. What am I talking about? Let’s revisit the scenario.

So I was making a getJSON jQuery request to load all of the states a user is interested in from the DB.

The following was the original call:

 $.getJSON('<%= Url.Action("GetSelectedStates", "Profile") %>', function(data) {
                    for (var i = 0; i < data.length; i++) {
                        $("#stateSelection").trigger("addItem", data[i]);
                    }
                });

The user can then view the state information in a FCBK type control.

Now if the user deletes a state or adds one, the db will get updated on the form post event. Next time around the same getJSON call will be executed and the new states will be displayed.

Sounds easy right? Well it isn’t. Turns out, this works on every browser but IE. IE for some reason caches your JSON request. This means the JSON call is completely bypassed the second time around/and any subsequent times and your updates are never displayed again.

There are a couple of ways you can solve this issue:
1. Use a POST and add an additional parameter of “json”. However, I don’t quite like this approach.
2. FAKE the JSON request to be unique by adding a random parameter in the JSON call. This can be done rather easily. I can now do a DateTime.Now in the JSON call and then just accept that parameter from my controller. This DateTime.Now will always be different and thus will prevent your JSON calls from being cached.

Here is the modified getJSON method:

function loadStateData() {
 $.getJSON('<%= Url.Action("GetSelectedStates", "Profile") %>',
{ currentTime : '<%= DateTime.Now %>' },
function(data) {
 for (var i = 0; i < data.length; i++) {
 $("#stateSelection").trigger("addItem", data[i]);
 }
 });
 }

And here is my controller code:

public JsonResult GetSelectedStates(DateTime currentTime)
        {
            JsonResult result   = new JsonResult();
            Guid userId         = sessionService.GetLoggedInUserId();
            List stateSelections = physicianService.GetPhysicianStateSelections(userId);
            var data = (from s in stateSelections
                        select new
                        {
                            title = CacheServiceInstance.GetStateProvinceById(s.StateProvinceId).Name.Trim(),
                            value = s.StateProvinceId
                        }).ToList();
            result = Json(data);
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return result;
        }

This should take care of the issue! Enjoy!

Why Microsoft ASP.NET MVC framework?

03.08.10

At HyperTrends, we have started moving a lot of our development to using the Microsoft ASP.NET MVC Framework. This is a significant jump from ASP.NET but I strongly believe it is for the best. Two of our critical projects have now been implemented using MVC and I can definitely assure you that we’re already seeing the benefits of using MVC.

So why use MVC? Here are some of the reasons why I think you should use it:

Testability

ASP.NET MVC is built around the notion of testability. When you create a solution, you can actually create a test project and write your own tests using Visual Studio or NUnit. You can test your routes, your controllers, your views, your services, your repositories and everything that you can think of. This is a very, very good way to develop software. You are greatly reducing the risk in Software Development by adding testability right from the development phase.

Patterns & Practices

MVC offers you a whole set of patterns and practices to follow. It however, doesn’t preach any certain technology. You are free to implement your own as long as you follow the simple patterns of development. You can replace the View Engine, the default Controller factories, the way you use AJAX (either Microsoft AJAX or jQuery), the repository access mechanism (use OR/M like NHibernate, EF or Linq to Sql), dependency injection etc. This gives you complete control over everything. MVC is highly flexible and highly customizable out of the box and can be really extended any way you want.

Works with HTTP instead of against it

One of the biggest difference between MVC and ASP.NET classic is that ASP.NET classic went against the HTTP Protocol by adding the notion of state (using View State). MVC however uses the Http protocol to its advantage. You program against Http Get, Post, Delete etc and that makes things very intuitive and straightforward.

Absolute control over HTML

ASP.NET classic had a major drawback. The HTML emitted couldn’t be designed the way you wanted. Elements had funky names, the server side controls generated tables and if CSS was used, it wasn’t flexible enough to seamlessly transition a designer’s HTML into a Developer’s HTML.

This caused a lot of overhead for developers. We at HyperTrends still deal with issues in our classic ASP.NET web apps where we take in a designer’s CSS HTML and then spend endless hours converting it into a format that ASP.NET likes.

The end result is that a designer needs to fully understand ASP.NET Server controls in order to make this transition seamless. This means that one cannot outsource design + css tasks to designers who don’t understand ASP.NET Server controls. If we do, we have to write long specs with it to ensure that CSS is written in a way that makes it most compatible with ASP.NET HTML code.

Good news! MVC doesn’t impose any restrictions on your HTML format. In fact, the methodology allows you to write pure HTML code (if you want), or use the default HTML View engine, or even integrate with a 3rd party View engine. The control is in your hands.

Ajax, Ajax and Ajax

Every time I look at an app by 37Signals, I am totally blown away by some of the AJAX functionality. However, the good news is that I can do all of that in my MVC app now thanks to both the Microsoft AJAX library and the native jQuery integration within the MVC framework.

We have personally integrated a lot of 3rd party jQuery controls and AJAX behaviors in our applications. The end result is amazing.

I think that should give you good enough reasons to use the MVC framework. Here are some final miscellaneous reasons:

1. Programmers don’t write spaghetti code because the methodology doesn’t let you write it. Gone are the endless lines of code. They are replaced by simple controller actions calling services, which in turn call your DAL/Repository layer.

2. Layered programming using dependency injection ensures that code is manageable and easy to debug. Technical debt reduces significantly.

3. Everyone follows the same pattern of development – This is a significant improvement. In ASP.NET, your developers were free to write their method implementation the way they wanted. No two people had the same approach towards coding.

This caused headaches during technical code reviews and imparted no fixed structure towards coding. With the advent of MVC, this is totally eliminated. Everyone follows the same pattern of development thereby improving the overall software design process.

In Closing…

I hope you consider ASP.NET MVC framework as a strong candidate for all your future Web Development needs. Feel free to chime in on the comments if you need any help/guidance on the same. We have some interesting code snippets and sample projects to give out in the next few weeks. Stay tuned!

Till then, ROCK ON DEVELOPERS! ROCK ON!

Top Technologies .NET Developers Should Learn

03.07.10

Things are going to get very interesting in the Microsoft .NET space very soon. .NET programmers have primarily been overshadowed by the Google/Java and Apple/Objective C programmers when it comes down to consumer products (aka Android and iPhone apps). However, there is a wave coming and I strongly believe that .NET programmers will be able to do a lot more in the upcoming months than they could before.

Here are some of the top technologies that I think .NET developers should start learning immediately:

Silverlight

Microsoft Silverlight has often been compared to Adobe Flash for the obvious reasons. However, I strongly believe that Silverlight is so much more. Smooth Media Streaming technology, HTML embedding within Silverlight Canvas, a very strong integration with the underlying .NET framework etc. all make Silverlight a force to reckon with.

Microsoft recently announced that the Windows 7 Series Phone will leverage the power of Silverlight and XNA frameworks. This means developers who know and understand Silverlight will be able to leverage their knowledge into building great phone applications. Silverlight is a must know for all .NET developers seeking to build great applications for the future.

Here are some Silverlight links:
http://silverlight.net/

XNA

XNA allows users to develop games for the XBox and Microsoft platforms. Just like Silverlight, XNA is going to become the top technology to learn to create applications and games for virtually all future Microsoft products. I recently downloaded the PGR: Ferrari Edition on my Zune. Very, very impressive. I would start learning the XNA framework right away.

Here are some links:
http://creators.xna.com/en-US/
http://msdn.microsoft.com/en-us/aa937791.aspx

Microsoft Azure

The multiple screens and the Cloud vision is very close to becoming a reality. This video by Microsoft shows how close we are to that reality. Microsoft Azure is the backbone of this strategy and has been gaining a lot more traction. Steve Ballmer wants 90% of his employees working towards this vision. That should give you an idea on how serious Microsoft is about getting it right.

Developers should definitely invest some time learning Microsoft Azure. It would be very safe to say that Microsoft Azure will be the most requested technology in the coming years.

Here are some links:
http://www.microsoft.com/windowsazure/getstarted/

F#

Functional Programming is a paradigm of Software development aimed at dramatically reducing complexity of software and thereby improving developer productivity. F# is I believe every .NET programmer should start learning functional programming fundamentals and F#. Our generation is moving towards parallel processing and asynchronous processing at a very fast pace. F# also addresses these items including all of the other functional programming ideologies.

Here are some links:
http://msdn.microsoft.com/en-us/fsharp/default.aspx?ppud=4

With the RC of Visual Studio 2010 and the .NET 4.0, the SDK’s for all of the above mentioned technologies are now available for developers.

Without further ado, I think it is time to get coding! Rock on, developers! Rock On!

Welcome to our .NET Blog

02.26.10

At HyperTrends, our primary strength lies in developing applications using the Microsoft .NET framework. We have been playing with .NET from its beta days and have leveraged the entire framework in the past 10 years or so.
This blog is aimed at documenting .NET trends, tutorials, tips and other things related to .NET.

Hope you like reading out posts. Feel free to comment!