ASP.NET MVC (II. Data transmission)

Posted by jayshadow on Wed, 15 Dec 2021 05:04:11 +0100

catalogue

preface:

1. Data transmission

1.1,ViewData

 1.2,ViewBag

  1.3,TempData

2. Use of Session

2.1. How Session works:

2.2. Advantages and disadvantages of Session:

2.3. Session failure (do not set if not necessary):

2.4. Use of Session:

3. Set transfer and traversal:

3.1 traversal of set list

3.2 collection dictionary traversal

preface:

ASP.NET MVC is the most concise, convenient, efficient and fast method of small website development. This paper can let a Xiaobai learn website development in the fastest way.

There is only one true heroism in the world:

Recognize what life really wants and still love it. Isn't the way to climb up more exciting than standing on the top?

1. Data transmission

The controller transfers a small amount of data to the view. There are three common types: ViewData ViewBag TempData

1.1,ViewData

ASP. Definition of ViewData attribute in ControllerBase class in net MVC 5 source code:

public ViewDataDictionary ViewData { get; set; }

ViewData itself is a ViewDataDictionary dictionary type, which is defined as follows:

public class ViewDataDictionary : IDictionary<string, object>{}

usage method:

controller:

/// <summary>
/// Get
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
    ViewData["Message"] = "Do you know the difference between a full meal and a full meal?";
    return View();
}

 

View:

@* In view  *@
<h2>@ViewData["Msg"]</h2>

Execution effect:

 1.2,ViewBag

controller:

ViewBag.Msg = "Temporary stimulation and lifetime happiness are more important?";

View:

<h2>@ViewBag.Msg</h2>

Execution effect:

  1.3,TempData

ViewData property and ViewBag property cannot transfer data across Action methods. When data needs to be transferred between multiple Action methods, TempData property can be used.

The TempData property is to save the data in the Session.

controller:

/// <summary>
/// Get
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
    TempData["Msg"] = "Temporary stimulation and lifetime happiness are more important?";
    return View();
}
public ActionResult About()
{
    return View();
}

Create [About.cshtml] view:

<h2>@TempData["Msg"]</h2>
<hr/>
<h2>But some people can't tell.</h2>

[Index.cshtml] view:

<a href="~/Test/About">Jump</a>

Execution effect:

Jump effect:

2. Use of Session

 ASP.NET page is "stateless", which means that every time a request is sent to the server, the server will generate an instance of the page. But sometimes, we want to share information between different pages, such as shopping cart, user login, etc Net provides us with a Session mechanism on the server side.

2.1. How Session works:

The Session mechanism of the server is based on the client, that is, the Session of the server will save the information of each client to the memory of the server. The specific process is as follows:
→ the client sends a request to the server
→ the server responds to the client and creates a Session and a unique Session ID for the client
→ store the Session ID as the key and the Session content as the value in the Session State Provider in the form of key value pairs
→ the client requests the server again with its own Session ID
→ the Session mechanism of the server takes the content from the Session State Provider and returns it to the client according to the Session ID of the client

2.2. Advantages and disadvantages of Session:

advantage:
● maintain user status and information across pages
● it is easy to use and can store any type
● be able to save the information of each client
● safe and transparent

Disadvantages:
● because the Session is stored in the memory of the server, with the increase of client requests, it is likely to affect the performance
● on the web In conig, if the mode attribute of the sessionState node is set to "StateServer" or "SQLServer", the object stored in the Session must be marked with [Serializable]. In this way, when storing and reading sessions, continuous serialization and deserialization will also affect performance

2.3. Session failure (do not set if not necessary):

<system.web>
    <sessionState mode="off" />
</sytem.web>

2.4. Use of Session:

controller:

Session["girl"] = "Girls don't sleep after 12 p.m. for a long time.";

View [Index.cshtml]

<a href="~/Test/About">Jump</a>

View [About.cshtml]

<h2>@Session["girl"]</h2>
<hr/>
<h2>It can promote the secretion of androgen in the body</h2>
<h2>Will: long beard, long leg hair, thick voice, become a real woman man.</h2>

Execute jump effect:

3. Set transfer and traversal:

Test object [GirlSix]:

[Serializable]
public class GirlSix
{
    /// <summary>
    ///Number
    /// </summary>
    public string id { get; set; }
    /// <summary>
    ///Creation time
    /// </summary>
    public DateTime createDate { get; set; }
    /// <summary>
    ///Nickname
    /// </summary>
    public string nickName { get; set; }
    /// <summary>
    ///Age
    /// </summary>
    public int age { get; set; }
    /// <summary>
    ///Introduction
    /// </summary>
    public string introduce { get; set; }
}

3.1 traversal of set list

controller:

/// <summary>
///Default test set
/// </summary>
/// <returns></returns>
public List<GirlSix> DefaultList()
{
    List<GirlSix> lists = new List<GirlSix>();
    lists.Add(new GirlSix() { id = System.Guid.NewGuid().ToString("N"), createDate = DateTime.Now, nickName = "Xin Xin Dong", age = 20, introduce = "Mr. Guo is one of his disciples." });
    lists.Add(new GirlSix() { id = System.Guid.NewGuid().ToString("N"), createDate = DateTime.Now, nickName = "Wang Xiaohan", age = 19, introduce = "There are beautiful women in the north, peerless and independent." });
    lists.Add(new GirlSix() { id = System.Guid.NewGuid().ToString("N"), createDate = DateTime.Now, nickName = "Niu Longzhu", age = 21, introduce = "Smile like peach blossoms bloom in March, and the breeze slowly intoxicates your face." });
    lists.Add(new GirlSix() { id = System.Guid.NewGuid().ToString("N"), createDate = DateTime.Now, nickName = "Yan Chunna", age = 21, introduce = "Pearl tassel rotating stars shaking,The flower vine is full of energy and the dragon and snake move." });
    lists.Add(new GirlSix() { id = System.Guid.NewGuid().ToString("N"), createDate = DateTime.Now, nickName = "Liu Zijia", age = 20, introduce = "Bright eyes are fond of gazing, auxiliary dimples bear power, magnificent appearance, beautiful and leisurely, and the end is a good flower king and rich peony." });
    lists.Add(new GirlSix() { id = System.Guid.NewGuid().ToString("N"), createDate = DateTime.Now, nickName = "Wei Huijuan", age = 21, introduce = "The pulse is in the middle of the eye, full of flowers." });
    return lists;
}
//Transfer value view
ViewBag.list = DefaultList();

View:

@{
    ViewBag.Title = "Main page";
}
@* In view  *@
<table class="table table-bordered table-hover table-striped">
    <tr class="info">
        <td>number</td>
        <td>Creation time</td>
        <td>nickname</td>
        <td>Age</td>
        <td>brief introduction</td>
    </tr>
    @foreach (var item in ViewBag.list)
    {
        <tr>
            <td>@item.id</td>
            <td>@item.createDate</td>
            <td>@item.nickName</td>
            <td>@item.age</td>
            <td><pre>@item.introduce</pre></td>
        </tr>
    }
</table>

Execution effect:

3.2 collection dictionary traversal

controller:

/// <summary>
///Default dictionary
/// </summary>
/// <returns></returns>
public Dictionary<string, Object> DefaultMap() {
    Dictionary<string, Object> map = new Dictionary<string, object>();
    map.Add("code",200);
    map.Add("message","Access successful");
    map.Add("result",DefaultList());
    return map;
}
//Transfer value view
ViewBag.list = DefaultMap();

View:

Return code:@ViewBag.list["code"]
<hr/>
Return message:@ViewBag.list["message"]
<table class="table table-bordered table-hover table-striped">
    <tr class="info">
        <td>number</td>
        <td>Creation time</td>
        <td>nickname</td>
        <td>Age</td>
        <td>brief introduction</td>
    </tr>
    @foreach (var item in ViewBag.list["result"])
    {
        <tr>
            <td>@item.id</td>
            <td>@item.createDate</td>
            <td>@item.nickName</td>
            <td>@item.age</td>
            <td><pre>@item.introduce</pre></td>
        </tr>
    }
</table>

The effects are as follows:

Chapter II [II. Data transmission] is completed.

[I. controller and view: https://laoshifu.blog.csdn.net/article/details/120126288]

[II. Data transmission: https://laoshifu.blog.csdn.net/article/details/120127320]

Topics: ASP.NET mvc