Wednesday, March 21, 2012

Custom ViewState in MVC

Just in case anyone want to build his own ViewState here is an example:

The model is serialized JSON (you can write JavaScript to read any information even if it is not rendered in a separate control) and then deserialized.

For security (if your model contains information that should not displayed in the HTML source, you can encrypt it then decrypt it with the post back), also compression will be helpful for smaller response/request. (I think this is why MVC is better in performance, because NO ViewState :) )

Also in the code after getting the data from the ViewState, you can compare it with the data retrieved from the model to know which field is updated, you can then call a method accordingly (the same as TextBox1_Changed(...., ....) in ASP.NET forms), this can be done as well from JavaScript by injecting in the hidden field using jQuery whenever the value of any control is updated.

In the form add a hidden field that will hold the viewstate, plus all your other controls.

You can also add in the ViewState a bool value indicating the IsPostBack, and use this value in the form or the code.

Blessings of working on large real-world projects

Working on large real-world projects can offer numerous blessings and benefits, both professionally and personally. Here are some of the key...