ASP. NET MVC 5 Web Programming 5-How page values are passed

Source: Internet
Author: User
Tags tag name actionlink

This article will describe the page pass-through method of MVC, including: Back end to the front end of the value (Controller to view value), the front end of the value (view to the controller), the value of the action and action.

Review

We review the most commonly used methods of transmitting values between pages in the ASP. NET WebForms, in the following ways:

a). QueryString (also called URL value)

b). Session

c). Cookies

d). Application

e). Server.Transfer

The usage and pros and cons of these methods are not described here, and in the later chapter we will use MVC's value-transfer method to compare and explore.

The following formally starts the MVC page pass-through method

Controller passes value to view

1. ViewBag

Usage:

Write in the controller

" Hello World. ";

Reception received

@ViewBag. Test123

Description: ViewBag is a dynamic type, and the key = = Test123 In the above example can specify any type.

2. ViewData

Usage:

Write in the controller

viewdata["Test123""Hello World". This is ViewData";

Reception received

@ViewData ["Test123"]

Description: ViewData is a dictionary type that inherits from the Idictionary<string,object> interface

3. TempData

Usage:

Write in the controller

tempdata["tmpdata""I am tempdata ... ";

Reception received

@TempData ["Tmpdata"]

Description: TempData is also a dictionary type, inheriting from the Idictionary<string,object> interface

4. Model

This is the most common way for beginners to use the value. In the previous article, we had this sentence in the page code of the Razor view:

@model ienumerable<mvc5demo.models.userinfoviewmodel>

Then our list of information is this:

<tbody>@foreach (varIteminchModel) {                     <tr> <td> @Html. displayfor (P. = Item. UserName) </td> <td>@ (item. Sex = =0?"female":"male") </td> <td> @Html. displayfor (P. = Item. Age) </td> <td> @Html. displayfor (P. = Item. Dept) </td> <td> @Html. ActionLink ("Edit","Edit","UserInfo",New{Id=item. Userid.tostring ()},NULL) @Html. ActionLink ("Delete","Delete","UserInfo",New{id = Item.} Userid.tostring ()},New{onclick="return confirm (' Confirm Delete"+item. username+"the record? ');"}) </td> </tr>                    }                </tbody>

As the code shows, since our model is a generic collection, it is convenient to take the data out of the collection.

In the background controller, how to write it?

         Public actionresult Index ()        {            return View ("UserInfo", Gettestdata ()); // Gettestdata () returns a generic collection        }

As the code shows, you only need to return the view when you specify the data object for the view.

View to controller pass value

1. Using Html.BeginForm (...) method to submit the form

    @using (Html.BeginForm ("actionname","controllername")    {        <div> form content </div>        <div>...</div>        <input type=" Submit " value=" Submission Form " />    }

Description: Writes the <form> start tag to the response. When a user submits a form, the request is processed by an action method that specifies an action for the controller.

(Use the using to close the form, no longer described below.) )

2. Using Html.beginrouteform (...) method to submit the form

 @Html. Beginrouteform ( "  route name   ", new  {controller = "  userinfo  , Action="  save  , UserID = Model.userid, userName = <div> form content </div> <div>...</div> <input type=  " Value="   submit form   "/>"  

Description: Same as Html.BeginForm (), but uses routing to submit the form with different parameters.

3. The Action property submission for the traditional form form

    <form id="postform" action="@Url. Action ("Save" ) )" method="post">            <div> form content </div>            <div>...</div>            <input type="submit" value= " Submit Form " />    </form>

Description: Use traditional HTML form native tags.

4. Submit the form using Ajax, Ajax.beginform (...)

    @Ajax. BeginForm ("actionname"new ajaxoptions {url="", onsuccess=" ", httpmethod="get"  })    {        <div> form content </div>        <div>...</div>        <input type="submit" value= " Submit Form " />    }

Description: Submits a form form using asynchronous methods.

5. jquery and Ajax submission forms

Omitted... Not in the article discussion scope.

6. Form parameter passing

6.1 Full parameter transfer

[HttpPost]  Public ActionResult Save (string username,int sex,int age,string dept)

Description: The HTML tag name and parameter names need to be the same.

6.2 Entity pass-through parameters

[HttpPost]  Public ActionResult Save (Userinfoviewmodel Item)

Description: The page uses the @model binding type

6.3 Form Collection Pass parameter

[HttpPost]  Public ActionResult Save (FormCollection FC)

Explanation: Need to parse formcollection, such as:

New Userinfoviewmodel (); TryUpdateModel<UserInfoViewModel> (UserInfo, FC);

6.4 Traditional Way

Using HttpContext, we can also use the following objects in MVC:

Application,server,session,request,response,cache ...

Controller passes the value (value between action) to the controller

1. Redirecttoaction

1.1 Passing entity objects

         Public actionresult Index ()        {            return redirecttoaction ("Index""Home")  New"zhangsan"1"HR " });        }

Description: In Userinfocontroller, when the page loads, create a new entity type, and jump to the homepage.

Receive:

     Public class Homecontroller:controller    {        public  actionresult Index (Userinfoviewmodel model)        {            //  Process the value            of model //...

1.2 Passing common parameters

         Public actionresult Index ()        {            return redirecttoaction ("Index""Home")  New"zhangsan"});        

Receive:

     Public class Homecontroller:controller    {        public actionresult Index (string userID ,string  userName)        {             // handling userid, username value             //...

2. TempData

            tempdata["userName" "zhangsan";             return Redirecttoaction ("Index2");

Receive in INDEX2:

string userName = tempdata["userName"]. ToString ();

Description: TempData can be passed between different actions in the same controller and have a ' one-time access ' trait. Pay special attention when using.

Comparison of WebForms with the value of the transmission

1. The background cannot obtain the value of a page element by non-submission because there is no ' server control '; MVC uses native HTTP, which is "stateless".

2. Cannot use (nor do) ViewState.

3. Use a unique mechanism to pass the value (Viewdata,viewbag ... And so on).

A simple entry-level demo

Development tools: VS2013

Function point: User Information list, to realize the increase of user information, delete, change, check function.

Click I download

Summarize

This paper mainly introduces the method of page transfer of ASP. NET MVC5. and provides a simple demo for the needs of friends reference learning.

Because my level is limited, such as the article has the wrong place also please point out, and the generous enlighten! The author is here to express his thanks.

This chapter is the last of the "Getting Started" phase of the ASP. MVC5 article will focus on advanced techniques and some technical or questionable questions. Please look forward to ~

I hope this article will be of help to you.

ASP. NET MVC 5 Web Programming 5-How page values are passed

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.