Persisting model state in ASP.NET MVC using Serialize HTMLHelper

ASP.NET MVC 2 futures assembly provides a HTML helper method Serialize that can be use for persisting your model object. The Serialize  helper method will serialize the model object and will persist it in a hidden field in the HTML form. The Serialize  helper is very useful when situations like you are making multi-step wizard where a single model class is using for all steps in the wizard. For each step you want to retain the model object's whole state.


The below is serializing our model object. The model object should be a Serializable class in order to work with Serialize helper method.

<% using (Html.BeginForm("Register","User")) {%>

<%= Html.Serialize("User",Model) %>

This will generate hidden field with name "user" and the value will the serialized format of our model object.

In the controller action, you can place the DeserializeAttribute in the action method parameter.

[HttpPost]              

public ActionResult Register([DeserializeAttribute] User user, FormCollection userForm)

{

    TryUpdateModel(user, userForm.ToValueProvider());

    //To Do

}

In the above action method you will get the same model object that you serialized in your view template. We are updating the User model object with the form field values.

4 Comments

Comments have been disabled for this content.