Several ways for ASP. NET MVC controller to pass value to view

Source: Internet
Author: User

The last few posts mention the difference between MVC and WebForm, mainly the MVC controller and view decoupling the traditional webform form and background code, this post simply describes how the controller in MVC is going to view the value.

A bit of MVC basic know, controller to view the value of the main four ways, the following will be introduced.


1) ViewBag


ViewBag is a dynamic type, and you can add a property assignment directly when you use it viewbag.myname

Controller code:

        Public ActionResult Index ()        {            viewbag.name = "Zhoujiang";            Viewbag.message = "Welcome to MVC design mode ~ ~";            return View ();        }
View Code:

    <div>                <!--when you create a TextBox using HtmlHelper, the name matches the key in ViewBag, and the value is automatically bound to        @Html. TextBox ("name")        @ViewBag. Message            </div>
Effect Display:


2) ViewData


ViewData is valid only for the current action, which is a dictionary collection that reads the corresponding value from the key value;

Controller code:

Public ActionResult Index ()        {            viewdata["name"] = "Zhoujiang";            viewdata["Message" = "Welcome to MVC design Pattern ~ ~";            return View ();        }
     View Code:

<div>                <!--when you create a TextBox using HtmlHelper, the name matches the key in ViewData, and the value is automatically bound to        @Html. TextBox ("name")        @ViewData ["message"]            </div>
Effect Display:


3 ) tempdata


using TempData is the same as using the ViewData method, but it can be used to pass values between different actions, which ViewData cannot do.

Controller code:

    public class Mvccontroller:controller    {public           actionresult Index1 ()        {            tempdata["name"] = "Zhoujiang";                        return View ();        }        Public ActionResult Index2 ()        {            string strName = tempdata["Name"]. ToString ()            return View ();        }
      In the above Code, index () adds a key-value pair to tempdata, assuming we first request the action of index and then request INDEX2 This action, then in Index2, We can get the key-value pairs that were added to the tempdata before. Interestingly, if INDEX2 is requested again, the value of MyName read from TempData will be null. This is because TempData is similar to a temporary session, when Acion executes it as a global object in memory, and once the action is done, it frees up memory space, which is the biggest difference between it and ViewData.   


4) Model


Controller through model value should be used in MVC is the most common method of transmission, through the strong type binding, in view can be easily through the model's corresponding properties to get the desired value.

Model Code:

    public partial class Yzadministratorentity    {public        yzadministratorentity ()        {this            . yzclearrecordentity = new hashset<yzclearrecordentity> ();            This. yznotifyinfoentity = new hashset<yznotifyinfoentity> ();        }                    Public System.Guid ID {get; set;}        public string AdminPassword {get; set;}        public string AdminName {get; set;}        public bool isused {get; set;}        [Required (allowemptystrings = false, ErrorMessage = "User ID cannot be null")]        public string Administratorid {get; set;}        public string Adminlevel {get; set;}            Public virtual icollection<yzclearrecordentity> yzclearrecordentity {get; set;}        Public virtual icollection<yznotifyinfoentity> yznotifyinfoentity {get; set;}    }
View Code:

Strongly typed bindings:

@model model.yzadministratorentity

automatically match the property values of model and label or Txtbox through LINQ:
            <div> <span class= "Editor-label" > @Html. Label ("Number:") </span> <span class= "Editor-field" > @Html. Editorfor (A = A.administra TorID) @Html. validationmessagefor (model = model. Administratorid) </span> </div> <div> <span class = "Editor-label" > @Html. Label ("Password:") </span> <span class= "edit Or-field "> @Html. Editorfor (A = A.adminpassword) </span> </di                v> <div> <span class= "Editor-label" > @Html. Label ("real name:") </span> <span class= "Editor-field" > @Html. Editorfor (A = A.adm Inname) </span> </div>

Summary: About the view and controller of the value of learning, the first contact is through the model transfer value, feel very convenient, and TempData, ViewData and viewbag are not very understanding, through the gradual deepening of learning, Only slowly to the latter three have a further understanding. This reminds me of rice teacher's "Eating theory", to what new knowledge of new things to experience a process from unfamiliar to familiar, but if you can put them and existing knowledge or understanding of the physical connection, will undoubtedly accelerate the process of your exploration, will also be your new exploration easier.

Several ways for ASP. NET MVC controller to pass value to view

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.