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.

Published Saturday, March 6, 2010 12:04 AM by shiju
Filed under: ,

Comments

# re: Persisting model state in ASP.NET MVC using Serialize HTMLHelper

Wednesday, April 7, 2010 2:40 AM by Raj

Where do I find the extension method Html.Serialize for framework 3.5?

# re: Persisting model state in ASP.NET MVC using Serialize HTMLHelper

Wednesday, April 7, 2010 2:48 AM by shiju

@Raj - Html.Serialize available in the ASP.NET MVC 2 futures assembly. This can download from codeplex.com at aspnet.codeplex.com/.../41742

# re: Persisting model state in ASP.NET MVC using Serialize HTMLHelper

Thursday, June 24, 2010 6:47 AM by jorgebg

WTF! Persisting model state in ASP.NET MVC? looks like viewstate... Do you want persistance: What about session state

# re: Persisting model state in ASP.NET MVC using Serialize HTMLHelper

Thursday, July 1, 2010 5:29 PM by evi

In the code above it should be <%= Html.Serialize("user",Model) %> ... User is in lowercase here.

Leave a Comment

(required) 
(required) 
(optional)
(required)