asp.net mvc 页面传值的方法总结

转自:http://msprogrammer.serviciipeweb.ro/2012/01/15/usual-methods-to-transfer-data-from-page-to-page-in-asp-net-mvc/

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

?


1

2

3

4

5

6

7

public class ModelTransfer

    {

        public int Age { get; set; }

        public string Name { get; set; }

    }

We have the first View1Index) 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 .

?


1

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

?


1

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

?


1

2

3

4

5

@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" />

}

?


01

02

03

04

05

06

07

08

09

10

[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

?


1

<a href=‘@Url.Action("ServerAction")‘>click me</a>

?


1

2

3

4

5

6

7

8

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

?


1

<a href=‘@Url.Action("TransferCookies")‘>click me</a>

?


1

2

3

4

5

6

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

This entry was posted on Sunday, January 15th, 2012 and is filed under ASP.NET MVCfull. You can follow any responses to this entry through RSS 2.0. You can leave a response, or trackback from your own site.

时间: 2024-11-02 23:41:44

asp.net mvc 页面传值的方法总结的相关文章

Asp.net mvc页面传值-- dropdownlist

后台传值 List<ConfigParamInfo> paramList = configParamBLL.GetModelList(" and parentID=1"); ViewData["UserState"] = new SelectList(paramList,"value","name"); 前台页面 @Html.DropDownList("userstate", ViewData[

ASP.NET页面传值的方法

ASP.NET页面传值的方法 From:Refresh-air 在面试的时候,经常会遇到这样的问题,其实我们会对其中的几种方法比较熟悉,因为项目中经常使用.但是要全面的回答ASP.NET中页面传值的方式,估计往往很难全面.一. 使用QueryString变量 QueryString是一种非常简单也是使用比较多的一种传值方式,但是它将传递的值显示在浏览器的地址栏中,如果是传递一个或多个安全性要求不高或是结构简单的数值时,可以使用这个方法. Response.Redirect( "target.as

ASP.NET跨页面传值——Application

ASP.NET跨页面传值 Application对象的作用范围是整个全局,也就是说对所有用户都有效.它在整个应用程序生命周期中都是有效的,类似于使用全局变量一样,所以可以在不同页面中对它进行存取.它和Session变量的区别在于,前者是所有的用户共用的全局变量,后者是各个用户独有的全局变量. 可能有人会问,既然所有用户都可以使用application变量,那他可以用在什么场合呢?这里举个例子:网站访问数.多个请求访问时都可以对它进行操作. 优点: 1.使用简单,消耗较少的服务器资源. 2.不仅能

ASP.NET跨页面传值——Cookie

ASP.NET跨页面传值 Cookie,这个也是大家常使用的方法,Cookie用于在用户浏览器上存储小块的信息,保存用户的相关信息,比如用户访问某网站时用户的ID,用户的偏好等,用户下次访问就可以通过检索获得以前的信息.所以Cookie也可以在页面间传递值.Cookie通过HTTP头在浏览器和服务器之间来回传递的.Cookie只能包含字符串的值,如果想在Cookie存储整数值,那么需要先转换为字符串的形式. 注意: Cookie与Session一样,都是什对每一个用户而言的,但是有个本质的区别,

ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view)

原文:ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view) 在本节中,您将验证电影控制器生成的编辑方法(Edit action methods)和视图.但是首先将修改点代码,使得发布日期属性(ReleaseDate)看上去更好.打开Models \ Movie.cs文件,并添加高亮行如下所示: using System; using System.ComponentModel.DataAnnotations; using System.Data.

ASP.NET跨页面传值——Server.Transfer

ASP.NET跨页面传值 这个才可以说是面象对象开发所使用的方法,其使用Server.Transfer方法把流程从当前页面引导到另一个页面中,新的页面使用前一个页面的应答流,所以这个方法是完全面象对象的,简洁有效. Server.Transfer是从当前的ASPX页面转到新的ASPX页面,服务器端执行新页并输出,在新页面中通过Context.Handler来获得前一个页面传递的各种数据类型的值.表单数据.QueryString.由于重定向完全在服务器端完成,所以客户 端浏览器中的URL地址是不会

ASP.NET跨页面传值——QueryString

ASP.NET跨页面传值 跨页面传值是学习asp.net初期都会遇到的的一个问题,但总结下来,跨页面传值常用的有QueryString,Session,Cookies,Application等几种. 那么现在就简单说下第一种方法--QueryString. QueryString QueryString是一种非常简单的传值方式,他可以将传送的值显示在浏览器的地址栏中.如果是传递一个或多个安全性要求不高或是结构简单的数值时,可以使用这个方法.但是对于传递数组或对象的话,就不能用这个方法了. 这种方

[转]ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view)

在本节中,您将验证电影控制器生成的编辑方法(Edit action methods)和视图.但是首先将修改点代码,使得发布日期属性(ReleaseDate)看上去更好.打开Models \ Movie.cs文件,并添加高亮行如下所示: using System; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace MvcMovie.Models { public class Movie

ASP.NET跨页面传值技巧[总结]

个人网站:http://www.51pansou.com .net视频下载:.net视频教程 .net源码下载:.net源码 关于页面传值的方法,我就我个人观点做了些总结,希望对大家有所帮助. 1.  使用QueryString变量 QueryString是一种非常简单的传值方式,他可以将传送的值显示在浏览器的地址栏中.如果是传递一个或多个安全性要求不高或是结构简单的数值时,可以使用这个方法.但是对于传递数组或对象的话,就不能用这个方法了.下面是一个例子: a.aspx的C#代码 private