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

后端 未结 4 1956
情书的邮戳
情书的邮戳 2020-12-09 05:55

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 \'caus

相关标签:
4条回答
  • 2020-12-09 06:38

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

    0 讨论(0)
  • 2020-12-09 06:38

    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.

    0 讨论(0)
  • 2020-12-09 06:39

    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.

    0 讨论(0)
  • 2020-12-09 06:48

    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.

    0 讨论(0)
提交回复
热议问题