Define ViewState on the WebForm code page (for example,. aspx. cs:
ViewState["test"] = "abc"; |
On the displayed page (such as. aspx), you can use:
Output
The Controller in MVC defines:
ViewData["test"] = "abc"; |
It can also be used in a view:
Output
Is there a difference between ViewState and ViewData?
Some people may say that if EnableViewState = "false" is set in WebForm mode, ViewState cannot be used. Is this true? After testing, it is found that no matter whether the EnableViewState is true or false, the preceding <% = ViewState ["test"] %> value can be normally output.
That's not to say that ViewState can be used to replace ViewData in WebForm as in MVC?
MSDN defines ViewState:
A dictionary for retrieving status information. This information allows you to save and restore the view status of the server control among multiple requests on the same page.
The code is defined as follows:
protected virtual StateBag ViewState { get; } |
We can see that only the get method is used in this attribute, that is, this attribute is read-only. You may say that ViewState ["test"] = "abc" is used above "; isn't it being assigned a value? This is because ViewState is an instance of the StateBag class, while the StateBag class implements a dictionary interface, so ViewState can store data in the form of key-value pairs, however, you cannot perform operations like this: ViewState = new StateBag... because ViewState is read-only, ViewData in MVC can be read and written, its code is defined as: public ViewDataDictionary ViewData {get; set ;}
The difference is that ViewState is read-only, and ViewData is read-write and can be redefined)
Difference 2: ViewData can be used for all view pages in an http request, such as. aspx/. ascx.... ViewState can only be used for front-end display pages where the current back-end code file is located.
For example, if control. ascx exists in default. aspx, ViewState ["test"] defined in default. aspx. cs cannot be obtained in control. ascx.
Difference 3: ViewState is mainly used to record the status information of the server control. The asp.net engine will automatically fill in the status information of the server control, so it is best not to use ViewState to store your own values.
Difference 4: In order to ensure that ViewState can correctly record the status information of the server control, the values in ViewState should all be serialized in the string form ), viewData can be used to save various types of values.
I have discovered these points. I hope you can continue to add them. please correct me if they are incorrect. Thank you.
- ASP. NET 3.5 chart controls
- Implement ASP. net mvc framework by yourself
- Methods to prevent multiple user logins in ASP. NET
- Construct an ASP. NET Website using XML + XSLT + CSS + JQuery
- Introduction to how to understand the performance of LINQ statements in ASP. NET