C# 在 Asp.net mvc 中维护视图状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1285547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:40:27  来源:igfitidea点击:

Maintaining viewstate in Asp.net mvc?

c#asp.netasp.net-mvcviewstate

提问by Goober

One of the major reasons for using webforms is the ease of being able to maintain viewstate. I would like to build an asp.net mvc application so what options do I have for maintaining viewstate?

使用 webforms 的主要原因之一是能够轻松维护视图状态。我想构建一个 asp.net mvc 应用程序,那么我有哪些选项来维护视图状态?

Kind regards

亲切的问候

采纳答案by Robert Harvey

ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method. Once the controller method has been called, what you do with those values is up to you.

ASP.NET MVC 不使用传统意义上的 ViewState(即在网页中存储控件的值)。相反,控件的值被发布到控制器方法。调用控制器方法后,您对这些值的处理取决于您。

ASP.NET MVC will persist the values of the controls long enough for you to validate them and (if needed) to round-trip them back to your page for editing or correction. If the controls validate, you can persist them to a database or other data store, where they will be available for subsequent GET requests.

ASP.NET MVC 将保留控件的值足够长的时间,以便您验证它们并(如果需要)将它们返回到您的页面进行编辑或更正。如果控件通过验证,您可以将它们保存到数据库或其他数据存储中,以便后续 GET 请求可以使用它们。

回答by jeef3

If you're wanting to make for example, a Wizard styled form, you could create a Serializable class to retain the viewstate:

例如,如果您想要制作一个向导样式的表单,您可以创建一个 Serializable 类来保留视图状态:

[Serializable]
public class MyWizard
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

You could then serialize this class and use it in a similar way to using ViewState (as a hidden field in the form).

然后,您可以序列化此类并以类似于使用 ViewState(作为表单中的隐藏字段)的方式使用它。

回答by jan salawa

You can imitate view state by serializing model in view using MVC3Futures project

您可以通过使用MVC3Futures 项目在视图中序列化模型来模拟视图状态

All you have to do is to serialize model and encrypt it in view.

您所要做的就是序列化模型并在视图中对其进行加密。

@Html.Serialize("Transfer", Model, SerializationMode.EncryptedAndSigned)

And in controller add deserialized attribute.

并在控制器中添加反序列化属性。

public ActionResult Transfer(string id,[Deserialize(SerializationMode.EncryptedAndSigned)]Transfer transfer)

回答by Saqib A. Azhar

Due to its basic design of maintaining the business layer separate from presentation layer, MVC Framework does not allow to preserve the State over HTTP,

由于其维护业务层与表示层分离的基本设计,MVC 框架不允许通过 HTTP 保留状态,

However Cookies, Serializable classes,ViewData and ViewBag are good ways to preserve the state in MVC.

然而 Cookies、Serializable 类、ViewData 和 ViewBag 是在 MVC 中保留状态的好方法。