ASP.NET MVC - Is there a way to simulate a ViewState?

笑着哭i 提交于 2019-11-27 01:59:01

问题


I have the following situation... In a certain View, the user must select the initial hour, the final hour and the weekday. But, I can't save this informations to DB 'cause I need to save my whole page and I need the primary key of the primary table, but that's not the point.

So, while I don't save these data to DB, I'm saving to a Session. I was told to save to a cookie, but it appears that cookies have a size limit. So, I'm saving to a Session.

Buuuut, I was also told that I could save these informations (hours and weekday) to the user page, simulating a ASP.NET ViewState...

Does anyone know how to do this?? Does anyone know how to save temporarily these data withou using cookie or Session??

Thanks!!


回答1:


Hidden input fields won't help?

<%= Html.Hidden(...) %>

Update (serializing an object to base64):

var formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, myObject); // myObject should be serializable.
string result = Convert.ToBase64String(stream.ToArray());

When you want to fetch it back:

var formatter = new BinaryFormatter();
var stream = new MemoryStream(Convert.FromBase64String(hiddenFieldValue));
var myObject = (MyObjectType)formatter.Deserialize(stream);

Make sure you validate the data stored in the field when you use it as the client might change it. ViewState takes care of this automatically.

Side note: ASP.NET uses LosFormatter instead of BinaryFormatter to serialize ViewState as it's more efficient or ASCII based serialization. You might want to consider that too.




回答2:


TempData["MyData"], mind you this will only last one round trip.




回答3:


You could save a javascript array on the client... and then transmit all the information when the user ultimately saves.

You have to work a little more, but in the end it pays off.

I heavily use jQuery to do stuff like that, it's easier than it seems.




回答4:


If you just want to save the data for that request and the next request I'd recommend using Tempdata, else I'd recommend using Mehrdad`s answer.



来源:https://stackoverflow.com/questions/669492/asp-net-mvc-is-there-a-way-to-simulate-a-viewstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!