Clearer MVC

In every application there are some variables that are set by the ASP.NET  application(  ASP.NET_SessionId  cookie ) and some that are set by the programmer( cached data in Application/Session/Cache/Cookies and so on).

I wanted every time to have a page where I can “clear” / delete those – and not found. So it’s the Clearer project.

It consists of :

  1. ClearerController with 2 Actions:   Index and DeleteItem
  2. 2 Views : Index.cshtml and EditAppData.cshtml
  3. Different Models:
    • SourceData  – enum  – can be  :  None ,        Application ,        Cache ,        Session ,        Cookies
    • AppData –  maintains Key/Value and SourceData pairs
    • ListAppData – loads data from Application , Cache , Session , Cookies  – and deletes.

To make an example, I have put in the Application_Start and Session_Start different values. So the screen is the following:


What I learn from the code:

  1. The Cookies, Applications, Session , Cache items can be easily converted to an DictionaryEntry and the code can be like this:
     DictionaryEntry de = new DictionaryEntry(item, sess[item.ToString()]);
     AddNew(de, SourceData.Session);
  2. Code must be error prone – what if some item in Session is null ? So , if I have the Key, all is good:
    private void AddNew(DictionaryEntry de, SourceData sd)
                AppData ap = new AppData() { source = sd, Key = de.Key.ToString() };
                    var obj = de.Value;
                    ap.Value = (obj == null) ? Null : obj.ToString();
                catch (Exception ex)
                    ap.Value = string.Format(ErrorToString, ex.Message);
  3. The dog-food is good: I have followed my advice from msprogrammer.serviciipeweb… and it works ( used for Remove )
            public JsonResult DeleteItem(string TheKey, int Source)
                    var lad = new ListAppData();
                    lad.DeleteItem(TheKey, (SourceData)Source);
                    return Json(new { ok = true, message = "" });
                catch (Exception ex)
                    return Json(new { ok = false, message = ex.Message });
  4. When you pass strings in Javascript, there is a simple way to encode: HttpUtility.JavaScriptStringEncode
    <a href="javascript:removeItem('@HttpUtility.JavaScriptStringEncode(Model.Key)','@((int)Model.source)','@id')">Remove</a>

Possible uses:

  1. For developers –  when they want to see what happens when a cache item no longer exists
  2. For developers – to put to site admins some simple tool to reload data from Cache/Application . Just edit the LoadAll function to load only Cache/Application Winking smile
  3. For developers  – to test easily the session. Just delete ASP.NET_SessionId  cookie – you will get another one when you refresh the page.

You can view online at
The project could be found at and have all – source code, downloadable project .

Next week it will be a Nuget item.

For more features , please leave me a comment here or on codeplex at issues
Nuget package at

This software is free



This is an MVC add-on to add a messaging system to any MVC application. It costs me 0$ to make this program ( not yet finished, but free source at  and the related posts are at )

Home Computer – already done for browsing the internet.

Download Visual Studio Express – free .

Download Sql Server Express – free.

Download latest bits of EF 4.2 – to work with SqlServer Compact too – free.

(Connection to internet : 25 $ – but was already done for browsing the internet)

Installing and configuring software on my PC – 0 $.

All I have done is to sit on my home desk and tapping into the keyboard. But this is does not costs , right?

Making, Planning, testing, deploying – 0$.

[quote from= ]

So if you’re a magazine, website, corporation, sports team, or advertiser developer who wishes to use this photo  software , please don’t   come and ask to use it for free, or in exchange for credit or “exposure”.


Do not give feedback . Just rant about how bad code smells ,about how OOP and SOLID and Design Patterns are not made clear and how Testing is not properly handled. After all, it is free , right?

Usual Methods to transfer data from Page To Page in ASP.NET MVC


In ASP.NET ( like in PHP and other Web frameworks) there are 2 clear entities: Server ( code on the WebServer ) and Client( the HTML interpreted by the browser and javascript).

Server and Client shares same cookies – means Client and Client both can read and write cookies.

Transfer from the Client to Server happens when

a) you click a link : the information to transfer is query string . That means, http://…/a?x=y&a=b will send information y ( associated to key x) and b( associated to key a). This is called a GET

b) you press a submit button to send a FORM : the information is values of select and input. This is called a POST.

c) you send information via javascript ( including AJAX) . Usually this can involve a PUT, a GET, or other ( see REST ).

d) Creating/Modifying and send cookies. The sending happens automatically by the browser .

Transfer from the Server to Client

a)sending text(HTML)/binary data. . The interpretation is done by the browser( how to display html, how to display send file …)

b) Creating/Modifying and send cookies . Browser will do automatically this.

ASP.NET WebForms way:

For ASP.NET Webforms the modalities to transfer are detailed by Peter Bromberg , .


I want to discuss from ASP.NET MVC perspective. In MVC we have 2 distinct objects: VIEW and ACTION. Both happens to run on the Server .

  • The ACTION can return a VIEW or ( or a redirect to) another ACTION or simply a FILE
  • The VIEW processes a Model ( and a ViewBag/ViewData) and sends the text( HTML) data to the Client .

Instead of PAGES , we will discuss of VIEWS – because the VIEWS sends HTML data to the Client.

So, to transfer data between View1 to View2 in MVC is reduced to this:

a) Page1 transfer data to the server ACTION1( by a,b,c,d methods in the Preamble )

b) The Action receives the values as his parameters ( by binding) and can do this:

b1) Return a different View ( using some logic :

if( a )

return View1(Model1);


return View2(Model1);

b2) Returning a Redirect to ACTION2 ( that return View2) or simply return the result of this action

return RedirectToAction(Action2(<parameters>)); //Used in Post/Request/GET,

return Action2(<parameters>);

Resuming: Transfer betweem PAGE to PAGE in ASP.NET MVC is really transfering from ACTION to ACTION , besides the cookie that can be transferred directly by the browser.

9 Modalities to transfer data from Page to Page in ASP.NET MVC

Enough theory, let’s do some code. We have a Model to transfer named ModelTransfer

public class ModelTransfer
        public int Age { get; set; }
        public string Name { get; set; }


We have the first View1( Index) and a second View2(Transfer) that will server as an example. Also, we will have the more ACTIONS – one for each example of transfer – all are using the TRANSFER action as an ultimate resort do see the View.

Method1 : Transfer directly to the second View/Action .

<a href='@Url.Action("Transfer", new { Age = 42, Name = "Andrei Ignat" })'>click me</a>
public ActionResult Transfer(ModelTransfer m)

Method2 Index sends POST data to a [HttpPost] Index action, that performs some calculations and return a redirect.Usefull in PRG

@using (Html.BeginForm()) { 
<input type="text" id="Age" name="Age" value="42" />
<input type="text" id="Name" name="Name"  value="Andrei Ignat"/>
<input type="submit" value="Click me" />

        public ActionResult Index(ModelTransfer m)
            //save to the database the data 

            //this is for transferring alert data - such an "Completed saving" message to the user 
            TempData["displayalert"] = " this is from Index POST action!";
            //used in PRG 
            return RedirectToAction("Transfer", new ModelTransfer() { Age = m.Age, Name = m.Name });            

Method3: No data send. The ServerAction just make some data to be transferred to the Transfer view, by TempData

<a href='@Url.Action("ServerAction")'>click me</a>
 public ActionResult ServerAction()
            //You can put also into the Session / Application /Cache depending on your specifications
            TempData["MyModel"]=new ModelTransfer(){ Age = 42, Name = "Andrei Ignat"};
            TempData["displayalert"] = "this is from Server action!";
            return RedirectToAction("Transfer");

Method4: No data send. The ServerAction just make some data to be transferred to the Transfer view, by Cache

Method5: No data send. The ServerAction just make some data to be transferred to the Transfer view, by Session

Method6: No data send. The ServerAction just make some data to be transferred to the Transfer view, by Application

Method7: No data send. The ServerAction just make some data to be transferred to the Transfer view, by HttpContext Items

Method8: By Cookies

<a href='@Url.Action("TransferCookies")'>click me</a>
 HttpCookie cook = new HttpCookie("Transfer");
            //usually you put here more , but now I do not want to interfere with other methods
            cook.Expires = DateTime.Now.AddSeconds(1);
            cook.Value = "from transfer cookies";
            return RedirectToAction("Transfer");

Method9: By Javascript /Ajax.
It is an entire post by itself and you can see here:


In this post you have seen 9 methods to transfer data in MVC. As a bonus, the page dispolays also a message with Javascript( usefull for messaging like “Data Saved to database” messages to the user.
The code source you will find here:

Transfer Data Page to Page
It is made with Razor and MVC3 – but you can replace Razor with aspx and MVC3 with MVC2 also.

If you think I can improve this post, please leave some comment.


I used here hard coding values. Please learn about T4MVC and Html.EditorFor !

To learn more about ASP.NET MVC visit

Default TempDataProvider is based on Session. There is one more , based on cookies.

Please do the exercises to gain self knowledge about MVC

friday links 12

  1. Find & Purchase Data Subscriptions | Windows Azure Marketplace
  2. Would A Ponzi By Any Other Name Smell As Bad? | ZeroHedge
  3. Troy Hunt: ASP.NET session hijacking with Google and ELMAH
  4. Troy Hunt: Free eBook: OWASP Top 10 for .NET developers
  5. StructureMap and ASP.NET MVC 3 – Getting Started
  6. CuBox
  7. Unit Testing Myths and Practices
  8. This Photograph Is Not Free
  9. Richard Stallman Was Right All Along
  10. Programming Isn’t Fun Any More
  11. Matt Wrock’s Blog | Microsoft blogging platform gains 33% performance boost after adopting RequestReduce
  12. Matt Wrock’s Blog | Adopt RequestReduce and see immediate Yslow and Google Page Speed score improvements not to mention a faster site!
  13. The Joel Test: 12 Steps to Better Code – Joel on Software
  14. Developer declares ‘I am done with the Freemium Business Model’ | ITworld
  15. University accuses Oracle of extortion, lies, ‘rigged’ demo in lawsuit | The Industry Standard – InfoWorld
  16. calvin.jpg (JPEG Image, 900×628 pixels)
  17. NuGet Package of the Week #10 – New Mobile View Engines for ASP.NET MVC 3, spec-compatible with ASP.NET MVC 4 – Scott Hanselman
  18. The Seven Habits of Spectacularly Unsuccessful Executives – Forbes
  19. Everything for free, always: how Facebook ads show us the sad state of the Internet
  20. Eight Different Ways to Transfer Data from One Page to Another Page
  21. Stop using AutoMapper in your Data Access Code | Blog | DevTrends
  22. Visual Representation of SQL Joins – CodeProject®
  23. I, Interface – CodeProject®
  24. MVC Techniques with JQuery, JSON, Knockout and C# – CodeProject®
  25. The 11 Best Science Books of 2011 | Brain Pickings
  26. Alexander Beletsky’s Development Blog: Using ASP.NET MVC Validation Mechanism without ASP.NET MVC
  27. The Flinch eBook: Julien Smith: Kindle Store
  28. Best Practices for Handling Transient Conditions in SQL Azure Client Applications | Windows Azure Customer Advisory Team (CAT)
  29. jQuery UI Development & Planning Wiki / Template-Comparison
  30. ASP.NET MVC 3 and the @helper syntax within Razor – ScottGu’s Blog
  31. High-Performance ASP.NET Caching — Visual Studio Magazine
  32. Free Databases in the Window Azure Marketplace — Visual Studio Magazine
  33. Duck Programming
  34. Writing an automatic debugger in 15 minutes (yes, a debugger!) « TripleEmcoder
  35. Creating Bookmarklets for Fun and Profit | Think Vitamin
  36. Math doesn’t suck, you do.
  37. –
  38. A geek with a hat » Why programmers work at night
  39. ASP.NET MVC + Selenium + IISExpress
  40. SQL Azure Performance and Elasticity Guide – TechNet Articles – Home – TechNet Wiki
  41. 6 Books Every Programmer Should Own
  42. 10 Websites On How To Be A Better Programmer
  43. A Professor explained Marketing to MBA students « Pulkit Arora
  44. 91 Ways to become the Coolest Developer in the World « Pulkit Arora
  45. Orchard Project
  46. Extensions – Ninject
  47. Chapter 1 – Welcome to the Library
  48. Microsoft in 2011: How 13 Big Developments Shaped the Tech Giant
  49. HTML EMAIL BOILERPLATE v 0.5 updated 11/5
  50. Conditional Filters in ASP.NET MVC 3
  51. ASP.NET MVC Diagnostics Using NuGet
  52. Conversion from type ‘Object’ to type ‘String’ is not valid. : The Official Microsoft ASP.NET Forums
  53. How I Lost, Regained and then Turned Down an MVP Award – .NET & Funky Fresh – – Just the Tasty Bits
  54. Projects |
  55. Progressively enable the mobile web with ASP.NET MVC 4, HTML5, and jQuery Mobile | BUILD2011 | Channel 9
  56. Code First Migrations: Beta 1 ‘With-Magic’ Walkthrough (Automatic Migrations) – ADO.NET team blog – Site Home – MSDN Blogs
  57. Code First Migrations: Beta 1 Released – ADO.NET team blog – Site Home – MSDN Blogs
  58. Five Things You Should Stop Doing in 2012 – Dorie Clark – Harvard Business Review
  59. Signs that you are a bad programmer (Bad Programmers)
  60. This is why I don’t give you a job – Andor Jakab
  61. A Shiny New Me • HTML5 Boilerplate In Visual Studio 2010
  62. 9GAG – Can live with them can’t f**k without them


My first Nuget project: Hydrating.  Also a Codeplex project : 

It can re-make an object by adding items of “property/value”

It comes in 2 flavors: .NET 2.0 ( reflection ) and .NET 4  ( expression).

Sample Usage:

Sample usage:
var Model = new HydrateGeneric<MyModel>();
Model.AddNewProperty("OneProp", "bb");
Model.AddNewProperty("newData.StartDate", DateTime.Now.AddDays(1).ToString());
Model.AddNewProperty("newData.SecondProp", "AB");
Model.AddNewProperty("newData.aOne.ThirdProp", "XXX");
var data = Model.NewObject();


It comes from a Paulo Morgado idea from . However, his initialization does not specify property name – so it’s rather error prone if you do not specify properties + values in right order. I have somewhat improved by


Model. AddNewProperty("OneProp", "bb");



Chosen and Jquery and MVC

In the MVC forums I have seen a reference to Chosen. From the description here:
“Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly.”
It look beautifool – and I see the opportunity to improve my toolbox. I said: “I will do in 10 minutes”. Well, it did take longer – but not so long.

I will make an example my tutorial mvc and ajax – since it does not require any database.

So I download the source from , put the .js in Scripts folder, the .css in Contents folder and registered in JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\_Layout.cshtml

<link href="@Url.Content("~/Content/chosen.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/chosen.jquery.min.js")" type="text/javascript"></script>

Here is the code : ( from JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\EditorTemplates\EditEmployeeViewModel.cshtml ):

     var idcombo = "#"+ ViewData.TemplateInfo.GetFullHtmlFieldId("cmbemp" + Model.Employee.IdEmployee);
     $(document).ready(function () {

         $("@idcombo").chosen({ no_results_text: "No results matched"});



And I said, this will be all.

Not so: see the picture – the names does not show up:


First I was thinking that it does not select the item. After several attempts, I realize the “…” ( three dots) – that means the width was not enough.
Next move, since I was in the javascript mood, was to add some javascript to adjust the width to fit:

So the code becomes:

$("@idcombo").chosen({ no_results_text: "No results matched" });

No difference. So I tried the opposite way:

$("@idcombo").chosen({ no_results_text: "No results matched" });

Now it matches:

And , thinking about a bit, it is better right in the Dropdown declaration :

@Html.DropDownList("cmbemp" + Model.Employee.IdEmployee, new SelectList(Model.DepartmentList, "IDDepartment", "NameDepartment", Model.Employee.Department.IdDepartment),new{ style="width:350px;"})


Integration of Chosen with MVC dropdown is rather simple. Add the .js, the .css, register in the page, add $(“@idcombo”).chosen() declaration and do not forget the width of the dropdown ( select )

Source code here
Later edit: Please add also

to the header

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.