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

First version of Messaging system


Realized the first version. When you logon on the system, the application sends you an email and you can see it.

Lots of thing done – however, the testing is not complete.

Logging was the difficult part- since I want to work with various loggers( LOG4NET, NLOG, MS TRACE, and so on). I required to a duck typing from  DeftTech. See logging assembly for more details.

You can download the files from– however, you may want to wait for a NuGET version.

If you want to help me further , please send me an email via

Jquery Ajax Request and MVC detailed

I have made a post about how to configure the MVC with Razor , Partial View and returning JSON.  It does not need a database – that also because it should be simple to download and see the mechanism.

The sample demonstrates:

  1. Cascading dropdown ( see the button Populate from action and Cascading drop down)
  2. Populating a table from a Partial View(see the button Add New Employee(jquery call action and render)
  3. How to handle  error from action ( press Save 2 )
  4. How to send id parameters (long) from javascript to action ( press Delete 1 or Delete 2)
  5. How to send objects(Employee) from javascript to action ( press Save 1 or Save 2)

The PartialView is made with Razor – but this does not matter. The project can be written as well in ASPX. mvc jquery razor cascading demo

I think that a featured programmer will understand fast the code . Now it’s the time for the beginner programmer.


  1. Ajax Request in the server should return true or false – never return  error. The error should come from network failure or incorrect IIS server communication.
  2. Cascading dropdowns: return a list and populate the dropdown in the request.
  3. To send only id – as in the url, put {. To send more data , use JSON.Stringify
  4. Returning PartialViews with data : the most easy way is to create an Action , send the data  to this action and return a Partial View. The attempt to re-do the data from an existing DOM Element in javascript is error prone.
  5. A View page must have a ViewModel ( named Model in MVC code ) . The ViewModel can contain data from multiple classes in order to have all data that the View needs. How do you construct this ViewModel ? Simple: think about the data the View needs.

Exemplification :

1.Ajax Request in the server should return true or false – never return  error.

The _Layout in MVC should contain this :

$(document).ready(function () {
                cache: false,
                error: function (x, e) {
                    if (x.status == 0) {
                        alert('You are offline!!\n Please Check Your Network.');
                    } else if (x.status == 404) {
                        alert('Requested URL not found.');
                    } else if (x.status == 500) {
                        alert('Internal Server Error.');
                    } else if (e == 'parsererror') {
                        alert('Error.\nParsing JSON Request failed.');
                    } else if (e == 'timeout') {
                        alert('Request Time out.');
                    } else {
                        alert('Unknown Error.\n' + x.responseText);

See as the JSON error are handled here – network, timeout, others. And in the server never return error – use this boilerplate

        public JSonResult ....
             var data = obtain data from the server....
   return Json(new {ok = true,mydata=data,  message = ""});
            catch (Exception ex)
                return Json(new {ok = false, message = ex.Message});

This way, the only code returned is ok – false or true.
The javascript that call this have this form

            url:...  ,
            data: .... ,
            contentType:"application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok) {
                    //do something with returndata.mydata
                else {
//this is an error from the server
                    window.alert(' error : ' + returndata.message);


See tha handling of if (returndata.ok)
2.Cascading dropdowns: return a list and populate the dropdown in the request.

Example in code: from an department id in the first dropdown the code will fill the employees for the department
Always begin with server code .

        public JsonResult GetEmployeesForDepartment(long id)
                //in real application made a better load / retrieving
                var emp = new employeeList();
                emp.RemoveAll(item => item.iddepartament != id);
                return Json(new { ok = true, data = emp, message = "ok" });
            catch (Exception ex)
                return Json(new { ok = false, message = ex.Message });

As you the first principle ( handle errors ) is applied and the data is filled and returned by

return Json(new { ok = true, data = emp, message = “ok” });

Then wrote an event( here cascadingdropdown) for the first dropdown

<select id="cmbDept" style="display:none" onchange="javascript:cascadingdropdown()"> 

Then code it

 function cascadingdropdown() {
        var idDept = $("#cmbDept").val();
        window.alert(" call cascading dropdown for iddepartment = " + idDept);
        var urlemp = '@Url.Action("GetEmployeesForDepartment")';
        var select = $('#cmbEmp');
            type: "POST",
            url: urlemp,
            data: { id: idDept },
            success: function (returndata) {
                if (returndata.ok) {

                    window.alert('employee data is on javascript,  populating combo ');
//empty the combo
//fill again 
                    $.each(, function (index, itemData) {


                else {
                    window.alert(' error : ' + returndata.message);



The filling of the second dropdown occurs on
$.each(, function (index, itemData) {
3. To send only id – as in the url, put {. To send more data , use JSON.Stringify
The code is when you press “Save” or “Delete” . For saving we should send the Name and the department id. For Delete , just the id.
Let’s begin with delete
In server code delete Action have only the id of the employee as a parameter:

    public ActionResult DeleteEmployee(int id)
//just delete it - not important code

So the client code will be simple:

function deleteEmployee(idemployee){
        window.alert('now delete ' + idemployee);
        var urlDelete = '@Url.Action("DeleteEmployee")';
            {id: idemployee}, // see here how we transmit an unique parameter
         function (returndata) 
                window.alert(' deleted!');
                $("#emp"+ idemployee).hide('slow');
                window.alert(' error : ' + returndata.message);                


So you see how the
DeleteEmployee(int id)
from server code correspond with
{id: idemployee}
from the client browser.

For saving an employee we will be happy to receive the Employee class:

        public ActionResult SaveEmployee(employee emp)

To receive such a parameter we will replicate employee structure in Javascript

function saveEmployee(idemployee) {
        window.alert('now save ' + idemployee);
        var urlSave= '@Url.Action("SaveEmployee")';
        var dept = $("#item_cmbemp" + idemployee).val();
        var name = $("#txtemp" + idemployee).val();
        //replicated structure as the emnployee class in server C# code
        var emp = {
            IdEmployee: idemployee,
            NameEmployee: name,
            iddepartament: dept
            data:JSON.stringify(emp),//use this in order to MVC binding to take place 
            contentType:"application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok) {
                    window.alert(' saved ');                    
                else {
                    window.alert(' error : ' + returndata.message);



So you see how the class instance parameter <strong>emp from server
SaveEmployee(employee emp)
corresponds with the client browser emp structure that is stringified to send to the server

 var emp = {
            IdEmployee: idemployee,
            NameEmployee: name,
            iddepartament: dept

4. Returning PartialViews with data :
Use the same Partial View that you use it for rendering an edit.

public ActionResult AddNewEmployee()
            EditEmployeeViewModel evm = new EditEmployeeViewModel();
            evm.DepartmentList = new departmentList();
            evm.Employee = new employee(0,"New !",evm.DepartmentList[0]);
            return PartialView("~/Views/Shared/EditorTemplates/EditEmployeeViewModel.cshtml", evm);//TODO: use T4MVC

And javascript code:

 function AddNew() {
        var urlAdd='@Url.Action("AddNewEmployee")';
        $.get(urlAdd, function (data) {
            window.alert(' new employee coming from action !');           
            $('#tableEmp > tbody:last').after( data);//add last the whole data


We are using a simple get – and we have “cached” to false ( see rule 1)

4. A View page must have a ViewModel ( named Model in MVC code ) . The ViewModel can contain data from multiple classes in order to have all data that the View needs
Look at the page mvc jquery razor cascading demo

It is clear we need the list of department( maybe cached somehow to not query all the time the database) and the employee (id, name) for each row of the table .
So this we will make:

  public class EditEmployeeViewModel
        public departmentList DepartmentList{get;set;}//need the list to put in dropdown
        public employee Employee { get; set; }// the editing employee
        public EditEmployeeViewModel()
        public EditEmployeeViewModel(int id)
            DepartmentList = new departmentList();
            var EmployeeList = new employeeList();


  1. Ajax Request in the server should return true or false – never return error.
  2. Cascading dropdowns: return a list and populate the dropdown in the request.
  3. To send only id – as in the url, put {. To send more data , use JSON.Stringify
  4. Returning PartialViews with data : the most easy way is to create an Action , send the data to this action and return a Partial View.
  5. A View page must have a ViewModel ( named Model in MVC code ) . The ViewModel can contain data from multiple classes in order to have all data that the View needs.

The download is here:
Jquery MVC Razor demo full

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.