Summary of data transmission between Controller and View in ASP. NET MVC3, mvc3controller

Source: Internet
Author: User

Summary of data transmission between Controller and View in ASP. NET MVC3, mvc3controller
In ASP. net mvc, data is often transmitted between the Controller and the View. Therefore, it is very important to master the data transmission methods between the two layers skillfully and flexibly. This article discusses from two aspects:
1. The Controller transmits data to the View. 1. Using ViewData to transmit data is defined as follows in the Controller:

ViewData[“Message_ViewData”] = “ Hello ViewData!”;
Then, read the ViewData data defined in the Controller in the View. The Code is as follows:
@Html.Encode(ViewData["Message_ViewData"])
In js, the data in ViewData is read as follows:
<pre name="code" class="javascript"><script type="text/javascript">    var viewData = '@ViewData["Message_ViewData"]';</script>
 
2. Using ViewBag to pass data is defined in Controller as follows: 
ViewBag.Message_ViewBag =  “ Hello ViewBag !”;
Then read the ViewBag data defined in the Controller in the View. The Code is as follows:
@Html.Encode(ViewBag.Message_ViewBag)

In js, the data in ViewBag is read as follows:

<script type="text/javascript">    var viewBag= '@ViewBag.Message_ViewBag';</script>
3. Using TempData to transmit data is defined in Controller as follows:
TempData[“Message”] = “Hello word!”;
Then read the TempData data defined in the Controller in the View. The Code is as follows:
@Html.Encode(TempData["Message_TempData"])
In js, the data in TempData is read as follows:
<script type="text/javascript">     var tempData = '@TempData["Message"]';</script>
4. to transmit data using Model, you must first create a Model object class:
public class HelloModel    {        private string _name;        public string Name        {            get { return _name; }            set { _name = value; }        }        private string _text;        public string Text        {            get { return _text; }            set { _text = value; }        }    }

When using Model to pass data, we usually choose to create a strong View when creating a View, as shown in:


Select the created HelloModel from the model drop-down list box.
After creating a strong View, the first line of View code is as follows:
@model Test.Models.HelloModel
The Model used by this View is "Test. Models. HelloModel"
Then read the data defined in the Model in the View. The Code is as follows:
@Html.Encode(Model.Name)
Js reads the data in the Model as follows:
<script type="text/javascript">     var modelName = '@Model.Name';</script>
Summary:

1. ViewData and TempData are weak data transmission methods, while Model-based data transmission is strongly-typed.
2. ViewData and TempData are completely different data types. ViewData is an instantiated object of the ViewDataDictionary class, while TempData is an instantiated object of the TempDataDictionary class.
3. TempData is actually stored in the Session. The controller obtains TempData from the Session and deletes the Session each time it executes the request. TempData can only be transmitted once in the controller, and each element can only be accessed once. It is automatically deleted after access.
4. ViewData can only be set in one Action method. It can be read from the relevant view page and is only valid for the current view. Theoretically, TempData can be set in an Action to read multiple pages. However, elements in TempData will be deleted after being accessed once.
5. In MVC3, View data can be accessed through the ViewBag attribute. In MVC2, ViewData is used. The use of ViewData is retained in MVC3. For the differences between them, refer to this article.

Use and difference of ViewBag, ViewData, and TempData in MVC3

2. The View transmits data to the Controller in ASP. net mvc, and transmits the data in the View to the Controller, which is implemented mainly by sending forms. The specific methods are as follows:
1. Read Form data through Request. Form. We define the following in the View layer:
@ Using (Html. beginForm ("HelloModelTest", "Home", FormMethod. post) {@ Html. textBox ("Name"); @ Html. textBox ("Text"); <input type = "submit" value = "submit"/>}
Note:
HelloModelTest is the corresponding Action name, and Home is the corresponding Controller name.
At the Controller layer, the code for reading Form data through Request. Form is as follows:
 [HttpPost]        public ActionResult HelloModelTest()        {            string name= Request.Form["Name"];            string text= Request.Form["Text"];            return View();        }
2. Read form data through FormCollection. We define the following in the View layer:
@ Using (Html. beginForm ("HelloModelTest", "Home", FormMethod. post) {@ Html. textBox ("Name"); @ Html. textBox ("Text"); <input type = "submit" value = "submit"/>}
At the Controller layer, the code for reading form data through FormCollection is as follows:
[HttpPost]        public ActionResult HelloModelTest(FormCollection fc)        {            string name= fc["Name"];            string text  = fc["Text"];            return View();        }
3. We define model binding in the View layer as follows:
@ Using (Html. beginForm ("HelloModelTest", "Home", FormMethod. post) {@ Html. textBox ("Name"); @ Html. textBox ("Text"); <input type = "submit" value = "submit"/>}
The default model binding method obtains the form value from the request. The following Edit Action takes a model image as the parameter (Album ):
[HttpPost]public ActionResult HelloModelTest( HelloModel model){    // ...}
When your Action method uses a model object as a parameter, the MVC runtime will use model binding to construct this parameter. By default, defamodelmodelbinder is used to bind the model. The preceding HelloModel is used as an example. defamodelmodelbinder Retrieves all available HelloModel attributes for binding the model. According to the naming conventions, defamodelmodelbinder can automatically get the corresponding value in the request to fill in the HelloModel object (it can also create an instance of the object to fill in)
In other words, if HelloModel has a Name attribute, the model binding will find the parameter named Name in the request. Note that I am talking about "request" instead of "form set. Model binding searches for values in all aspects of the request, including route data, query strings, and form sets. If necessary, you can also add custom values to provide information.
Model binding is not limited to Http Post and complex parameters (such as HelloModel). You can pass in an original simple parameter:
 public ActionResult HelloModelTest( string name,string text){    // ….}
In this scenario, model binding searches for the parameter name and text in the request.
Explicit model binding when an Action has a parameter, the model binding is executed implicitly. You can also use UpdateModel and TryUpdateModel in the Controller to explicitly call model binding. When UpdateModel is called, an exception is thrown if the model object is invalid or an error occurs during binding. TryUpdateModel does not throw an exception. It returns a Boolean value: If the binding is successful and the model is verified, true is returned; otherwise, false is returned.
[HttpPost] public ActionResult HelloModelTest () {HelloModel model = new HelloModel (); if (this. TryUpdateModel (model) {// binding successful} else {// binding failed }}

The model status is a by-product of model binding. Each time the biner binds a value to the model, it is recorded in the model status. You can check the model status after model binding to determine whether the binding is successful:
[HttpPost] public ActionResult HelloModelTest () {HelloModel model = new HelloModel (); this. tryUpdateModel (model); if (ModelState. isValid) {// binding successful} else {<pre code_snippet_id = "569649" snippet_file_name = "blog_20150102_21_3590846" name = "code" class = "csharp"> <span style = "white-space: pre "> </span> // binding failed
}}
If an exception occurs during model binding, the model status contains the attribute name, binding value, and error information that causes the exception. 


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.