asp.net-mvc-3serializationasp.net-mvc-futures

Ignoring properties when serializing


I'm pulling my hair out on this one.

I am trying to implement a multi-step wizard, and i'm using the Html.Serialize html helper in MVC3 Futures. This works well, except one of the properties in my model is a SelectList. I don't want this property serialized (and it blows up when it tries anyways).

I can't use [NonSerialized] because that only works on fields, not properties. I've even tried some of the other normal ways such as [XmlIgnore] (which I didn't think would work anyways).

Can anyone suggest an attribute that will ignore a property in a model when using Html.Serialize?

EDIT:

The error I get when I try to serialize is a InvalidDataContractException. There is this message:

Type 'System.Web.Mvc.SelectList' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

However, if I do this then I have to mark all the members with [DataMember] just to exclude 1 property, which seems kind of stupid.

UPDATE:

A quick example of this is this bit of code (make sure to add reference to System.Runtime.Serialization.dll):

Test.cs

[Serializable]
public class Test
{
    public int ID { get; set; }
    [IgnoreDataMember]
    public SelectList TestList { get; set; }
}

HomeController.cs

public ActionResult About()
{
    return View(new Test() { ID = 0, TestList = new SelectList(new [] {""})});
}

Home/About.cshtml

@using Microsoft.Web.Mvc
@model MvcApplication3.Models.Test 

@Html.Serialize("Test", Model)

This generates the InvalidDataContractException


Solution

  • public class MyViewModel
    {
        [IgnoreDataMember]
        public SelectList Items { get; set; }
    
        ...
    }
    

    or simply:

    public class MyViewModel
    {
        public IEnumerable<SelectListItem> Items { get; set; }
    
        ...
    }