Mvc&webform Control Study: The method of passing value

Source: Internet
Author: User

Just from WebForm development to MVC, if a slightly more complicated knowledge points like routing can also be temporarily put first (assuming that the default routing rules basically meet most requirements), there is a problem in the rapid development, I think it must be resolved immediately, That is, whether the WebForm in the same way applies to MVC. Then this article is divided into two parts to elaborate. The next step is to simply and quickly review the method of WebForm in the first place.

Part 1 the method of transmitting value in WebForm

Form Form Delivery (get/post)

aspx
<Type= "text" id= "txtname" name= "txtname" runat= "Server"/>
Aspx.cs
String txtname = request.form["txtname"]. ToString ();

Hide a field (as an example of an HTML server control)
<input type= "hidden" id= "Hduserid" runat= "Server"/>
Hduserid.value = "1";

Just use text labels and hidden fields for example. As long as the data submitted through the form form (containing hidden fields), regardless of the label. are in this way of passing values.

URL Delivery

1. Hyperlinks (take HTML tags as an example):

<a href="Default. aspx?param1=1111&param2=2222">Go</a>

2.PostBackUrl

<asp:button id="btncheckout" text="CheckOut" PostBackUrl ="~/default.aspx?" Userid=1" runat="Server" />//getvar userid=request.querystring["userId"]

The above is only an example of the <a> label and Postbckurl band parameter passing. All of the parameters passed through the URL address bar are URL-pass values.

built-in object delivery

1.response.redirect

//Page1stringURL ="default.aspx?p1="+ p1 +"&p2="+P1; Response.Redirect (URL,false); //Page2varP1 = request.querystring["P1"]. ToString ();varP2 = request.querystring["P2"]. ToString ();

2.server.transfer

//Default.aspx<input type="text"Id="txtname"runat="Server"/>//Default.aspx.csServer.Transfer ("~/default2.aspx",true); Server.Execute ("~/default2.aspx",true);//Default.aspx.cs Page_LoadResponse.Write (request.form["txtname"])

3.Session:

// Set session["name"] = txtname.value; // Get string name = session["name"]. ToString ();

4.Cookie:

// Set New HttpCookie ("mycookie", AA); RESPONSE.COOKIES.ADD (cookie); // Get HttpCookie MyCookie = request.cookies["mycookie"= mycookie.value;

5.Cache

I don't make a narrative about this, but I'll take a look at the detailed usage. ASP. NET Cache and its advanced usage

6.Application

// Set application["count"; // Get int count= (int) application["count"].;

7.ViewState

On this topic, I do not do too much narration, can read this article

Cross Page Posting (ASP. 2.0)

Two Concepts crosspagesource.aspx (source page) crosspagetarget.aspx (Landing page)

1. Get the value of the control for the source page

//Default.aspx (source page)<input type="text"Id="txtname"runat="Server"/><asp:button text="Test"runat="Server"Postbackurl="~/default2.aspx"/>//Default2.aspx.cs (Landing page)if(previouspage.iscrosspagepostback) {//gets the value of the control for the source pageResponse.Write (request.form["txtname"]);
Or Response.Write ((Previouspage.findcontrol ("txtname") asSystem.Web.UI.HtmlControls.HtmlInputText). Value);}

2. Get the source page property values

//Default.aspx (source page) <input type="Text"Id="Txtname"Runat="Server"/><asp:button text="Test"Runat="Server"Postbackurl="~/default2.aspxThe/>//default.aspx.cs public properties
Public string Name {
get {
return txtname.value;
}
}
//default2.aspx (Landing page)
<%@ previouspagetype virtualpath= "~/default.aspx"%>Default2.aspx.csif (previouspage.iscrosspagepostback) { // Gets the value of the property
Response.Write (previouspage.name);}

Note: PreviousPage need to make a non-null judgment

Part 2 MVC method of passing values

Before we begin to understand the various methods of ASP. NET MVC, let's take a look at the following diagram. It is an image that illustrates the way values are passed between different levels.

(from the Internet)

It is not difficult to see from the graph that there are viewdata, ViewBag, TempData in the unique pass-through method in ASP. Of course there are viewmodel and model. Of course, you may find this picture not perfect. The following changes are made:

viewdata\viewbag

For both of them, let's look at a set of controls:

(Pictures from the Internet)

Although ViewBag appears in ASP. NET MVC 3, it is essentially a viewdata that wraps a layer of dynamic (for this, you can look at this, which is no longer detailed here), which is the encapsulation of viewdata, so that when you look at the differences between them, It is not difficult for us to understand. Next look at the example:

Action:

 Public ActionResult Index () {    viewdata["Message1" "ThisMessage is Coming from ViewData";     " This Message was coming from ViewBag ";       return View ();}

View:

<div>    @ViewData ["Message1"]</div><div>     @ViewBag. Message</div>


Results:

As mentioned above, Viebag is actually a layer of dynamic viewdata, and we assign value to ViewBag, the value is actually stored in ViewData, the name of the dynamic property is saved as the key of the Viewdatadictionary, The value of the dynamic property is stored as a value of viewdatadictionary. To demonstrate this, we will make the above code changes, and then look at the results of the operation:

Sure enough, as the variable is re-assigned. Since they actually have the same name, and eventually they are all stored in a viewdatadictionary way, the later values are overwritten by the original. The same reason, even if the background does not make changes, we in the foreground through the @viewdata["Message" to fetch is the value of Viewbag.message:

Summary: ViewData, ViewBag is primarily the transfer of data from the controller level to the view level

TempData

TempData is the dictionary type of tempdatadictionary. Not only can it pass data from the action to the view, it can also be passed to the action action of subsequent requests. Next look at the example:

Controller

View

To directly demonstrate that TempData can pass data from one request to subsequent requests and from the controller to the view, I create the tempdata["BookData" directly in the testtempdata operation and pass it to the index operation. The data is then presented in the view of index. The results of the operation are as follows:

Next, we tried to refresh the page, and unfortunately it happened: the object was not referenced to an instance of the object. Debug found that the value of TempData has been changed to null:

This is determined by the life cycle of the TempData: TempData can only save data to its next request. This is actually related to the storage mechanism of the tempdata. The implementation mechanism of TempData can be seen in the following article: on the implementation mechanism of TempData in ASP. Of course, ASP. NET MVC also provides us with a way to implement TEMPDAA persisted data:

 Public ActionResult Index () {    = tempdata["bookdata" as book ;    Tempdata.keep ("bookdata");     //     return  View (book);}
View Code

This is also based on the Temdata implementation mechanism, which removes any key-value pairs that are not updated in TempData before the next request. So we update the response key by Keep.

ViewModel

 Public ActionResult Index () {    = tempdata["bookdata" as book ;    Tempdata.keep ("bookdata");     //     return  View (book);}

View:

<div>    ID: @Model. id<br/>    bookname: @Model. BookName<br/>     Author: @Model. Author<br/>    ISBN: @Model. ISBN</div>

Operation Result:

Other like session, application, Cookie, cache because it is based on the ASP, and the way used in the WebForm is the same, here do not repeat.

Note: Due to limited personal skills, understanding of some concepts may be biased, if you find any bugs in this article, please correct me. Thank you!

Finish.

Mvc&webform Control Study: The method of passing value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.