<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Marc Dormey &#187; asp.net</title>
	<atom:link href="http://www.marcdormey.com/index.php/tags/asp-net/feed" rel="self" type="application/rss+xml" />
	<link>http://www.marcdormey.com</link>
	<description>Software Finds, Programming Tutorials and Gadget Reviews</description>
	<lastBuildDate>Tue, 20 Jul 2010 14:52:40 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>ASP.NET MVC JQuery ScriptManager</title>
		<link>http://www.marcdormey.com/index.php/archives/asp-net-mvc-jquery-scriptmanager</link>
		<comments>http://www.marcdormey.com/index.php/archives/asp-net-mvc-jquery-scriptmanager#comments</comments>
		<pubDate>Fri, 23 Oct 2009 11:19:54 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[scriptmanager]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=250</guid>
		<description><![CDATA[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 &#8220;parts&#8221; which you could add to a page. The &#8220;parts&#8221; were highly customisable, thus you could have 3 instances of the same &#8220;part&#8221; on one page. The html and javascript [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8220;parts&#8221; which you could add to a page. The &#8220;parts&#8221; were highly customisable, thus you could have 3 instances of the same &#8220;part&#8221; on one page. The html and javascript rendered by the part would conflict with each other, because they had the same id&#8217;s and registered events.</p>
<p>I needed something similar to the old ASP.NET Script manager and the way that old ASP.NET used the &#8220;clientId&#8221; instead of the &#8220;htmlId&#8221; when dealing with html objects. The &#8220;clientId&#8221; was a generated unique key that prevented duplicated user controls conflicting with one another.</p>
<p>I found quite a few implementations of ScriptManager (<a href="http://pietschsoft.com/post/2009/08/13/Simple-ScriptManager-for-ASPNET-MVC.aspx">http://pietschsoft.com/post/2009/08/13/Simple-ScriptManager-for-ASPNET-MVC.aspx</a>, <a href="http://aspmvccombine.codeplex.com/">http://aspmvccombine.codeplex.com/</a>) for MVC, but none of them were solving my unique &#8220;htmlId&#8221; 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&#8230;</p>
<p>I decided to combine knowledge obtained from the two ScriptManager implementations, and create my own light-weight solution addressing both problems.<br />
Because I wanted the usage of this to be very simple, I created a fluent interface which I can use in all my parts&#8230;</p>
<p>This is what the end result looks like:</p>
<pre class="brush:csharp">&lt;% Html.ScriptManager()
     .CreateClientScript(GetUniqueId())
       .AddParam("SelectId", GetUniqueId("selectList"))
       .AddParam("SourceUrl", Url.Action("Index", "Person"))
       .Ready(() =&gt; {%&gt;
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
      &lt;%});%&gt;

&lt;% Html.ScriptManager().AddStaticMethod("populate_combobox", () =&gt;{ %&gt;
    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);
            }
        });
    }
&lt;%});%&gt;

&lt;div id="&lt;%=GetUniqueId() %&gt;_part"&gt;
 &lt;select id="&lt;%=GetUniqueId("selectList") %&gt;"&gt;&lt;/select&gt;
&lt;/div&gt;</pre>
<p>My &#8220;GetUniqueId()&#8221; function returns a combination of the PartId, PageId, but you can replace this with anything you fancy.<br />
The javascript that gets generated by this is:</p>
<pre class="brush:js">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);
        }
      });
    }</pre>
<p>Update: I have gone even further and added the concept of &#8220;SharedVariables&#8221; to the ScriptManager where the &#8220;SourceUrl&#8221; above and even the Json request is fired only once!</p>
<p>Here is my ScriptManager Class:</p>
<pre class="brush:csharp">public class ScriptManager
{
    private readonly HtmlHelper _helper;

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

          return (IDictionary&lt;string, ClientScript&gt;)_helper.ViewContext.HttpContext.Items["ClientScripts"];
       }
    }

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

         return (IDictionary&lt;string, Action&gt;) _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("&lt;script type=\"text/javascript\"&gt;");

     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("&lt;/script&gt;");
   }

   private static bool IsLast(IDictionary&lt;string, string&gt; parameters, string key)
   {
     var keys = parameters.Keys.ToList();
     return keys.Count &gt; 0 &amp;&amp; keys[keys.Count-1] == key;
   }
}</pre>
<p>Here is the ClientScript class:</p>
<pre class="brush:csharp">public class ClientScript
{
   private readonly IDictionary&lt;string, string&gt; _parameters = new Dictionary&lt;string, string&gt;();
   private Action _script;

   public IDictionary&lt;string, string&gt; 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;
     }
   }
}</pre>
<p>Here is my extension method:</p>
<pre class="brush:csharp">public static ScriptManager ScriptManager(this HtmlHelper helper)
{
    return new ScriptManager(helper);
}</pre>
<p>And then you only need to add this at the end of your master page:</p>
<pre class="brush:csharp">&lt;% Html.ScriptManager().Render(); %&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/asp-net-mvc-jquery-scriptmanager/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Yes/No Dropdownlist Extension for ASP.NET MVC</title>
		<link>http://www.marcdormey.com/index.php/archives/yesno-dropdownlist-extension-for-asp-net-mvc</link>
		<comments>http://www.marcdormey.com/index.php/archives/yesno-dropdownlist-extension-for-asp-net-mvc#comments</comments>
		<pubDate>Wed, 14 Oct 2009 09:51:21 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CSS/Html]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[html]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=222</guid>
		<description><![CDATA[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. [...]]]></description>
			<content:encoded><![CDATA[<p>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. </p>
<p>If you are asking a user &#8220;Do you agree with our terms?&#8221;, the general consensus is to assume that not clicking the box is &#8220;forgetting&#8221; to make a selection and warning me that &#8220;You have forgotten to tick our terms and conditions&#8221;. In this situation the case may be so, but what if I did not agree? What if the question was &#8220;Do you want to opt out of us sending you loads and loads of spam?&#8221; and simply not spotting this question.</p>
<p>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; &#8220;yes&#8221;, &#8220;no&#8221; and &#8220;did not choose&#8221;.<br />
Once again, I don&#8217;t simply rant, I also offer a solution&#8230; a very simple extension method which I love using for all my yes/no questions instead of checkboxes. In this case I made the &#8220;not selected&#8221; state 0.</p>
<p></p>
<pre class="brush:csharp">
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);
        }
</pre>
<p>PS: It also looks a bit neater and more uniform.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/yesno-dropdownlist-extension-for-asp-net-mvc/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Kaboom! &#8211; JQuery MVVM Framework for the web</title>
		<link>http://www.marcdormey.com/index.php/archives/kaboom-jquery-mvvm-framework-for-the-web</link>
		<comments>http://www.marcdormey.com/index.php/archives/kaboom-jquery-mvvm-framework-for-the-web#comments</comments>
		<pubDate>Wed, 30 Sep 2009 12:41:20 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mvvm]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=199</guid>
		<description><![CDATA[&#8220;Kaboom!&#8221; 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 [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-205" title="Screenshot" src="http://www.marcdormey.com/wp-content/uploads/2009/09/Screenshot1.png" alt="Screenshot" width="211" height="396" />&#8220;Kaboom!&#8221; 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 &#8220;jquery.forms&#8221; to submit all my forms via ajax POST and using &#8220;$.getJSON&#8221; 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 &#8220;Kaboom!&#8221;.</p>
<p>The first thing I worried about was testability. &#8220;QUnit&#8221; (<a href="http://docs.jquery.com/QUnit">http://docs.jquery.com/QUnit</a>) seems to be a very powerful testing framework that would probably give me more coverage than what I had before! UnitTesting &#8211; Check <img src='http://www.marcdormey.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So lets look at one of the samples in the codeplex download, specifically the Asp.Net MVC sample&#8230;</p>
<p>We start with a &#8220;Person&#8221; Model:</p>
<pre class="brush:csharp">public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}</pre>
<p>And a &#8220;PersonController&#8221; class which has a Search action:</p>
<pre class="brush:csharp">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 =&gt; p.FirstName.ToLower().Contains(searchString.ToLower()) ||
                p.LastName.ToLower().Contains(searchString.ToLower())).ToList());
    }
}</pre>
<p>Then we create a &#8220;SearchViewModel&#8221; js file and put this in our &#8220;ViewModels&#8221; folder like so:</p>
<pre class="brush:js">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");
    }
}</pre>
<p>And our &#8220;Search&#8221; view would hook up to our view model like so&#8230;</p>
<pre class="brush:xml">&lt;head runat="server"&gt;
    &lt;title&gt;Search&lt;/title&gt;
    &lt;% string version = DateTime.Now.Ticks.ToString(); %&gt;
    &lt;script type="text/javascript" src="../../ViewModels/Persons/SearchViewModel.js?id=&lt;%= version %&gt;"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/jquery-1.3.2.js?id=&lt;%= DateTime.Now.Ticks.ToString() %&gt;"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/json2.js?id=&lt;%= DateTime.Now.Ticks.ToString() %&gt;"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/kaboom.js?id=&lt;%= DateTime.Now.Ticks.ToString() %&gt;"&gt;&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
    Quick start shows how to communicate with an aspMVC controller.....&lt;br /&gt;
    &lt;input type="hidden" id="viewmodel" viewmodel="SearchViewModel" debug="0" /&gt;
    &lt;div id="Debug"&gt;&lt;/div&gt;
    Search:&lt;br /&gt;
    &lt;input type="text" bindto="SearchString" mode="TwoWay" /&gt;&lt;br /&gt;
    &lt;input type="button" value="Search" command="Search" /&gt;
    &lt;br /&gt;
    &lt;table bindto="SearchResults"&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;First Name&lt;/th&gt;
                &lt;th&gt;Last Name&lt;/th&gt;
                &lt;th&gt;Options&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            &lt;tr&gt;
                &lt;td&gt;$FirstName&lt;/td&gt;
                &lt;td&gt;$LastName&lt;/td&gt;
                &lt;td&gt;&lt;a href="#" onclick="alert('$FirstName')"&gt;Delete&lt;/a&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/body&gt;</pre>
<p>You can bind all your view actions to commands.</p>
<pre class="brush:xml">
&lt;input type=&quot;button&quot; command=&quot;Save&quot; value=&quot;Bound to Save command via jQuery(element).click()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type=&quot;button&quot; command=&quot;Save&quot; trigger=&quot;dblclick&quot; value=&quot;Bound to Save command via jQuery(element).dblclick()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type=&quot;button&quot; command=&quot;Save&quot; trigger=&quot;blur&quot; value=&quot;Bound to Save command via jQuery(element).blur()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type=&quot;button&quot; command=&quot;Save&quot; trigger=&quot;customaction&quot; value=&quot;Bound to Save command via jQuery(element).customaction()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;</pre>
<p>&#8230; and it has support for other controls and more complex bindings.</p>
<pre class="brush:xml">
&lt;select bindto=&quot;Person.Salutation&quot;
         datatextfield=&quot;Name&quot;
         datavaluefield=&quot;Id&quot;
         datasourceid=&quot;Salutations&quot;
         onbind=&quot;ProgrammaticallyBindIt&quot; &gt;
   &lt;option value=&quot;0&quot;&gt;[select]&lt;/option&gt;
&lt;/select&gt;</pre>
<p>There are loads of other examples, including binding to Tables, Divs, Spans, Checkboxes etc. You can download the framework <a href="http://kaboom.codeplex.com/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/kaboom-jquery-mvvm-framework-for-the-web/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Changing the target filename of TransmitFile in asp.net mvc</title>
		<link>http://www.marcdormey.com/index.php/archives/changing-the-target-filename-of-transmitfile-in-asp-net-mvc</link>
		<comments>http://www.marcdormey.com/index.php/archives/changing-the-target-filename-of-transmitfile-in-asp-net-mvc#comments</comments>
		<pubDate>Thu, 17 Sep 2009 12:39:35 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[file download]]></category>
		<category><![CDATA[output response]]></category>
		<category><![CDATA[transmitfile]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=160</guid>
		<description><![CDATA[Say a file has a physical filename of &#8216;xyz.pdf&#8217;, but when you send it to the user you want it to have a name like &#8216;myxyzbrilliantfilename.pdf&#8217;. 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 [...]]]></description>
			<content:encoded><![CDATA[<p>Say a file has a physical filename of &#8216;xyz.pdf&#8217;, but when you send it to the user you want it to have a name like &#8216;myxyzbrilliantfilename.pdf&#8217;. How do you change the target filename when transmitting files through the output stream of Response without it popping up a download dialog?</p>
<p>I have searched wide and wild and the only way you could do this is by modifying the &#8220;ContentDisposition&#8221; like so:</p>
<pre class="brush:csharp">Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// OR
Response.AddHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");</pre>
<p>The &#8220;attachment&#8221; setting opens a dialog to save the file with the correct name and the &#8220;inline&#8221; setting doesnt open a dialog, but ignores the filename!<br />
This is not the behaviour I am looking for, so I had a quick coffee and came up with the following very simple solution!</p>
<p>My solution came in the form of a new route in my mappings:</p>
<pre class="brush:csharp">
routes.MapRoute(
    "ResourceModulePdf", // Route name
    "ResourceModule/Pdf/{id}.pdf", // URL with parameters
    new
    {
        controller = "ResourceModule",
        action = "Pdf",
        id = "",
        sourceFilename = ""
    } // Parameter defaults
    );
</pre>
<p>and my &#8216;pdf&#8217; action:</p>
<pre class="brush:csharp">
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");
}
</pre>
<p>&#8230; and my FileResult</p>
<pre class="brush:csharp">
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);
    }
}
</pre>
<p>All we need to do now is construct our hyperlinks like so: </p>
<pre class="brush:xml">

<a href="ResourceModule/Pdf/mynewbrilliantname.pdf?key=actualnameondisk.pdf" target="_blank">Doc</a>
</pre>
<p>By default the &#8220;TransmitFile&#8221; method will take the name of the filename you used in your hyperlink and the result is exactly what we wanted!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/changing-the-target-filename-of-transmitfile-in-asp-net-mvc/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling dynamic resources with ASP.NET MVC</title>
		<link>http://www.marcdormey.com/index.php/archives/handling-dynamic-resources-with-asp-net-mvc</link>
		<comments>http://www.marcdormey.com/index.php/archives/handling-dynamic-resources-with-asp-net-mvc#comments</comments>
		<pubDate>Wed, 09 Sep 2009 14:59:05 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[actionresult]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[image handler]]></category>
		<category><![CDATA[imageresult]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=136</guid>
		<description><![CDATA[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&#8217;s features for free. (ie. querying, profiling, backup, synchronisation and not to mention speed)
In the past we [...]]]></description>
			<content:encoded><![CDATA[<p>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 (<a href="http://geekswithblogs.net/aghausman/archive/2009/02/28/configure-sql-server-2008-for-file-stream.aspx">read more</a>), keeping your resources in the database gives you all of Microsoft SQL Server&#8217;s features for free. (ie. querying, profiling, backup, synchronisation and not to mention speed)</p>
<p>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&#8230;</p>
<p>First we create an &#8216;ImageResult&#8217; class which will handle our output.</p>
<pre class="brush:csharp">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);
    }
}</pre>
<p>And then we simply create an action for our specific needs:</p>
<pre class="brush:csharp">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);
}</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/handling-dynamic-resources-with-asp-net-mvc/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JQuery function to populate a select box</title>
		<link>http://www.marcdormey.com/index.php/archives/jquery-function-to-populate-a-select-box</link>
		<comments>http://www.marcdormey.com/index.php/archives/jquery-function-to-populate-a-select-box#comments</comments>
		<pubDate>Fri, 04 Sep 2009 11:52:48 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=34</guid>
		<description><![CDATA[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 &#8216;populateSelect&#8217; method in a global .js file and use it throughout your project as &#8216;$.populateSelect(args&#8230;)&#8217;
ASP.NET MVC Action Method
public ActionResult GetUsers()
{
   [...]]]></description>
			<content:encoded><![CDATA[<p>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 &#8216;populateSelect&#8217; method in a global .js file and use it throughout your project as &#8216;$.populateSelect(args&#8230;)&#8217;</p>
<p>ASP.NET MVC Action Method</p>
<pre class="brush:csharp">public ActionResult GetUsers()
{
     var data = Service.QueryUsers()
           .Select(x =&gt; new {value = x.Id, text = x.Name});

      return Json(data);
}</pre>
<p>Usage:</p>
<pre class="brush:js">var url = "&lt;%=Url.Action("GetUsers", "UserController") %&gt;";

$.getJSON(url, function(data, textstatus) {
        $.populateSelect("#someSelectBox", data);
});
</pre>
<p>Global Method:</p>
<pre class="brush:js">
// 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);
        }
    });
};</pre>
<p>Removing all Items from a select list is just as simple:</p>
<pre class="brush:js">
$("#mySelectList")
   .find("option")
   .remove();
</pre>
<p>And lastly how to Append or Prepend items to the list:</p>
<pre class="brush:csharp">
// Add options to the end of a select
$("#mySelectList")
    .append("<option value='1'>New Item</option>");

// Add options to the start of a select
$("#mySelectList")
    .prepend("<option value='0'>Select...</option>");
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/jquery-function-to-populate-a-select-box/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
