asp.net-mvc-3 - 序列化时忽略属性

标签 asp.net-mvc-3 serialization asp.net-mvc-futures

我正在为这个而烦恼。

我正在尝试实现一个多步骤向导,并且我在 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/

相关文章:

.net - 无法序列化 SolidColorBrush

serialization - 字节完美一致性(序列化)是什么意思?

asp.net-mvc - 带有 lambda 表达式的 ASP.net MVC 操作 URL

.net - MvcContrib 与 MvcFutures

asp.net - 使用 ASP.Net MVC 3 构建一个简单的网站

c# - 如何在 MVC3 中更新没有回发的 View

java - 我的项目必须知道我要反序列化的类的具体类型吗?

ASP.NET MVC 3 RESTful 路由 : RouteData must contain an item named Action?

asp.net-mvc - 应用程序排队/网站流量管理

asp.net-mvc-3 - NHibernate.ObjectNotFoundException : No row with the given identifier exists