I cannot figure out how to do serialization with a DropDownList and am getting the error "Type 'System.Web.Mvc.SelectList' cannot be serialized." I am using serialization in a wizard form to persist the user inputs through the end and then to post a confirmation.
I am using the following in a view:
@using (Html.BeginFormAntiForgeryPost())
{
@Html.Hidden("myData", new MvcSerializer().Serialize(Model, SerializationMode.Signed))
...
@Html.DropDownListFor(m => m.RealEstate, Model.RealEstateList)
...
}
In my ViewModel (MyData), I have:
[Serializable]
public class myData
{
public int RealEstate { get; set; }
public IEnumerable<SelectListItem> RealEstateList { get; set; }
...
public MyData()
{
var realestatelist = new List<SelectListItem>() {
new SelectListItem { Text = "(Please select)" },
new SelectListItem { Value = "1", Text="Some text." },
new SelectListItem { Value = "2", Text="Some other text." }
};
this.RealEstateList = new SelectList(realestatelist, "Value", "Text");
}
}
Any help is greatly appreciated.
The SelectList does not support serialization. Try to use
IEnumerable<SelectedListItem>
,IList<SelectListItem>
orList<SelectedListItem>
in your controller and then create the SelectList in the view.Change controller similar to this:
And seeing your
RealEstateList
in the model is alreadyIEnumerable<SelectListItem>
you can make the SelectList in the view then to specify the value and text without converting the model property like this:The
SelectList
class can't be serialized, as the error is saying. If you need to serialize a set ofSelectListItem
objects you'll need to use a container that can be serialized, like aList<SelectListItem>
.You will need to convert your
List<SelectListItem>
back into aSelectList
inside your view, like: