Usual Methods to transfer data from Page To Page in ASP.NET MVC
Preamble:
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 , http://www.eggheadcafe.com/tutorials/asp-net/e653f028-01fb-4d0e-843b-058deae562a2/eight-different-ways-to-transfer-data-from-one-page-to-another-page.aspx .
ASP.NET MVC way:
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);
else
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, http://en.wikipedia.org/wiki/Post/Redirect/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" /> }
[HttpPost] 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"; Response.Cookies.Add(cook); return RedirectToAction("Transfer");
Method9: By Javascript /Ajax.
It is an entire post by itself and you can see here:
http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/
Summary
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.
Notes:
I used here hard coding values. Please learn about T4MVC and Html.EditorFor !
To learn more about ASP.NET MVC visit http://asp.net/mvc.
Default TempDataProvider is based on Session. There is one more , based on cookies.
Please do the exercises to gain self knowledge about MVC
Andrei, very good posting. It helps me a lot to understand MVC.
Thank you!
Andrei,
I am a little confused. The title promises to talk about transferring data from Page To Page; but then you say that Instead of PAGES , we will discuss of VIEWS – because the VIEWS sends HTML data to the Client. Those are completely different things (“instead of navigating in Danube, we will discuss navigating in Black Sea – because it has salt water”). Am I missing something?
I expected a discussion how to transfer data in the context of “installation wizard” or “product configurator” where you go through several client pages and have to retain information that is incomplete; will fail validation; or have other challenges like that. “View to View” (on the server) is a completely different and much simpler challenge. I’ve successfully used TempData that seems to be designed exactly for a use case like that and that you don’t even mention.
Am I wrong?
Felix
this is text “).The Page is what you see displayed in the browser .In ASP.NET MVC is the HTML result of a View – or simply the result of the Action ( think return Content(“
So it’s better to say about ACTIONS/VIEWS then about PAGES.
( However, you are right: I will improve it . I will update with a modality to transfer from View to View.)
Well, this kind of state keeping will definitely kill your scalability. Primary thing to keep in mind about HTTP is the stateless nature of its methods. Whenever you try to keep state, scalability suffers and you have to use some session affinity tricks to manage this.
REST way would be to bring transfer values as http method parameters.
Very good post Andrei, thank you, also very good reference to web forms page transfer.
Interesant!
In ASP.NET MVC ar mai fi o metoda, nu asa eleganta, similara cu Server.Transfer din WebForms, care foloseste Server.TransferRequest pentru a executa alt Controller/Action evitand un response redirect, si deci un roundtrip catre browser: http://stackoverflow.com/questions/799511/how-to-simulate-server-transfer-in-asp-net-mvc
Oricum, as evita metoda asta din aceleasi motive din care Server.Transfer e de evitat.
@Felix – indeed, on ASP.NET MVC there are no “pages” server-side.
@Dan is right – in ASP.NET MVC, when possible, I would avoid using in-memory Session, TempData or Application to keep application state between requests, even if it seems easier sometimes than using a database to keep session state (ex.: for a shopping cart or wizard-like UI) or a distribute cache like AppFabric cache for caching needs.
Sure, for small in-house web sites, with a few users and a single web server, there is no problem to keep state in-memory.
—–
Other than that, a View in ASP.NET MVC should be regarded as a more “passive” component – is receives a model, renders it and produces some HTML – that’s it – it does not communicate directly with other view, does not ‘pass’ data to them and so on..
The formatting of the of bold and italic makes the article quite difficult to read.
Hello james,
Could you please show me how to improve it?
Thank you,
Andrei
Great Article
Great Thanks…
Please suggest me how i will redirect to another domain server from controllers method using POST method, so that fields values will not be seen on page source.
POST does not redirect. You can use an iframe
Great post. Thanks for sharing this inforamtion on 9 methods to transfer data in MVC with clear explanation . I hope you will keep sharing more such informative articles.