Persisting model state in ASP.NET MVC using Serialize HTMLHelper

Posted by shiju on Weblogs See other posts from Weblogs or by shiju
Published on Sat, 06 Mar 2010 05:04:00 GMT Indexed on 2010/03/08 7:08 UTC
Read the original article Hit count: 1022

Filed under:

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.


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.

© Weblogs or respective owner

Related posts about ASP.NET

Related posts about ASP.NET MVC