in

Chennai .Net User Group

A platform that enables you to Learn, Share & Grow (India's first .Net user group)

Shiju Varghese's Blog

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.

Read the complete post at http://feedproxy.google.com/~r/ShijuVBlog/~3/oab5fq3hwsE/persisting-model-state-in-asp-net-mvc-using-html-serialize.aspx

Only published comments... Mar 06 2010, 07:04 AM by Shiju Varghese's Blog
Filed under: ,
Copyright © 2002-2008 Chennai .Net User Group. All Rights Reserved. Microsoft and Microsoft logo's are trademarks of Microsoft Corporation