Archive for July, 2008

Post

Ajax User Controls in ASP.Net MVC Preview 3

In .Net on July 29, 2008 by Matt Grande Tagged: , , , ,

I was taking a look into how to ajax up my website using the new ASP.Net MVC stuff, and I came across some difficulties. After using Ruby on Rails for the better part of the last year, I expected to be able to call render_to_string or something similar on a UserControl, and replace a div with that string.

I’m writing a basic product page, and the product can come in many colours. I opted to ajaxify the colour pagination.

The first thing I did was get JQuery into my project. JQuery is a javascript library that makes a lot of the more common AJAX and DHTML tasks easier.

function ChangeColorwayPage(pageNumber) {
  // Hide the element with the id of colorway1
  $("#colorway1").hide("slow");
  // Generate the URL of the ajax call
  url = '/ColorWay/ChangeColorWayPage/<%= ViewData.Model.Style_Number %>/' + pageNumber;
  // Make a GET request to the URL.  The third parameter is the function that gets called after the ASP.Net code is run.
  $.get(url, null, function(data, status) {
    // Replace the HTML within the div 'colorway1'
    $("#colorway1").html(data);
    // Show the div again!
    $("#colorway1").show("slow");
  });
}

This was easy enough. The tricky part came when rendering a UserControl into a string. I opted to make a simple AjaxController that inherits from the base Controller object.

namespace YourApp.Controllers
{
    public class AjaxController : Controller
    {
        public string RenderToString(string UserControl, object model, Dictionary<string, object> ViewParameters)
        {
            // Replace the current context with a new context that writes to a string writer
            var existingContext = System.Web.HttpContext.Current;
            var writer = new StringWriter();
            var response = new HttpResponse(writer);
            var context = new HttpContext(existingContext.Request, response) {
                User = existingContext.User
            };
            System.Web.HttpContext.Current = context;

            // Add the ViewParameters to the ViewData hash
            foreach (string key in ViewParameters.Keys)
                ViewData[key] = ViewParameters[key];

            // Execute the action
            var viewResult = View(UserControl, model);

            // Execute the result
            viewResult.ExecuteResult(ControllerContext);

            // Restore the old context
            System.Web.HttpContext.Current = existingContext;

            return writer.ToString();
        }
    }
}

And now, in my ColorWay controller, all I have to do is this:

namespace YourApp.Controllers
{
    // Notice that it inherits from AjaxController
    public class ColorWayController : AjaxController
    {
        public string ChangeColorWayPage(string sellingStyleNumber, int pageNumber)
        {
            var productSpecs = new ProductSpec(sellingStyleNumber, false);
            var parameters = new Dictionary<string, object>();
            parameters["page"] = pageNumber;

            // Simply call RenderToString and you're good to go!
            return RenderToString("ProductSpecColorWay", productSpecs, parameters);
        }
    }
}

And with that, you should be good to go.

Happy coding!

Post

Single Quotes or Double Quotes?

In Ruby on July 25, 2008 by Matt Grande Tagged:

Josh Susser recently had an interesting article about Symbols. I had noticed that in many places where I thought I should be able to use symbols, I had to use strings (the routes file comes to mind).

Reading that post got me thinking about the differences between ’strings’ and “strings.” I knew that “strings” allowed you to do mid-string insertions:

puts "Your variable is #{my_var}."

On the other hand, with ’strings’ you had to use plus signs:

'Your variable is ' + my_var + '.'

I began to wonder if one was faster than the other. I had been told that single quotes were faster, but I had no idea if this was true, or by how much. I decided to run some benchmarks to see how quickly a string could be saved using the different methods.

require 'benchmark'
test_variable = 'a string'

Benchmark.bm do |x|
  x.report("Single Quotes, no insertion") {
    10000.times do
      str = 'Text without insertion'
    end
  }

  x.report("Double Quotes, no insertion") {
    10000.times do
      str = "Text without insertion"
    end
  }

  x.report("Single Quotes, with insertion") {
    10000.times do
      str = 'Inserting ' + test_variable + ' into a string.'
    end
  }

  x.report("Double Quotes, with insertion") {
    10000.times do
      str = "Inserting #{test_variable} into a string."
    end
  }
end

It turns out that single quotes are, in fact, slower than double quotes. Here’s my results:

                               user       system     total    real
Single Quotes, no insertion    0.000000   0.000000   0.000000 (  0.003485)
Double Quotes, no insertion    0.010000   0.000000   0.010000 (  0.002694)
Single Quotes, with insertion  0.010000   0.000000   0.010000 (  0.011286)
Double Quotes, with insertion  0.010000   0.000000   0.010000 (  0.009462)

Now keep in mind, my benchmarks were based on saving 10,000 strings. That means for every string using single quotes you have is wasting over 0.00000018 seconds. In other words, you would need to convert about 5.4 million single-quoted strings to double-quoted string to save one second of running time.

Happy coding!