我正在为这个而烦恼。
我正在尝试实现一个多步骤向导,并且我在 MVC3 Futures 中使用 Html.Serialize
html 助手。这很好用,除了我的模型中的一个属性是 SelectList
。我不希望这个属性被序列化(无论如何它都会在尝试时爆炸)。
我不能使用 [NonSerialized]
因为它只适用于字段,而不适用于属性。我什至尝试了一些其他常规方法,例如 [XmlIgnore]
(我认为无论如何都行不通)。
谁能推荐一个在使用 Html.Serialize
时忽略模型中属性的属性?
编辑:
我尝试序列化时遇到的错误是 InvalidDataContractException。有这条消息:
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.
但是,如果我这样做,那么我必须用 [DataMember]
标记所有成员,只是为了排除 1 个属性,这看起来有点愚蠢。
更新:
这方面的一个简单示例是这段代码(确保添加对 System.Runtime.Serialization.dll 的引用):
测试.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 [] {""})});
}
主页/About.cshtml
@using Microsoft.Web.Mvc
@model MvcApplication3.Models.Test
@Html.Serialize("Test", Model)
这会产生 InvalidDataContractException
最佳答案
public class MyViewModel
{
[IgnoreDataMember]
public SelectList Items { get; set; }
...
}
或者简单地说:
public class MyViewModel
{
public IEnumerable<SelectListItem> Items { get; set; }
...
}
关于asp.net-mvc-3 - 序列化时忽略属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9285439/