c# - 默认模型绑定(bind)器不绑定(bind) IEnumerable 中的 Nullable 类型

标签 c# asp.net-mvc asp.net-mvc-2 model-binding defaultmodelbinder

我有一个 Controller 操作,其定义如下所示-

public ActionResult ChangeModel( IEnumerable<MyModel> info, long? destinationId)

和模型:

public class MyModel
{
    public string Name; //Gets populated by default binder
    public long? SourceId; //remains null though the value is set when invoked
}

'Name' 属性在 Controller 操作中被填充,但是 SourceId 属性保持为空。 destinationId 是一个long? 参数也会被填充。

在单步执行 MVC(版本 2)源代码时,这是 DefaultModelBinder 抛出的异常。

从'System.Int32'类型到类型的参数转换 'System.Nullable`1[[System.Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' 失败,因为没有类型转换器可以在这些类型之间进行转换。

如果将模型更改为 long 而不是 long?,则默认模型绑定(bind)器设置该值。

public class MyModel
{
    public string Name {get;set;}; //Gets populated by default binder
    public long SourceId {get;set;}; //No longer long?, so value gets set
}

这是一个已知问题吗?由于 MVC 源代码经过优化,我无法单步执行大部分代码。

更新:发送的请求是一个使用 Json 的 Http POST,源 JSon 类似于 -

{"info":[{"Name":"CL1","SourceId":2}], "destinationId":"1"}

最佳答案

也许为时已晚,但我已经找到了解决方法。您可以在发送数据之前将 SourceId 字段转换为字符串。所以你的 JSON 数据看起来像

{"info":[{"Name":"CL1","SourceId":"2"}], "destinationId":"1"}

这在我的情况下有效(Int32 -> decimal?,ASP NET MVC 3)

关于c# - 默认模型绑定(bind)器不绑定(bind) IEnumerable 中的 Nullable 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5857680/

相关文章:

asp.net-mvc-2 - 选择聚合时如何处理 Linq to NHibernate 的 Fetch 异常?

C# WPF,日期选择器验证

c# - 未找到 WCF 端点

jquery - 客户端验证正在触发但不显示消息

c# - 运行 SqlQuery EF 时 FieldNameLookup.GetOrdinal 中的索引超出范围异常

c# - MVC .net 适合我的项目类型吗?

c# - ASP.NET MVC2-try/catch(throw?) block 的数量和位置

c# - 动态为ctor创建委托(delegate)

c# - 具有多个互相引用的集合的容器类的设计实践

c# - asp.net MVC 4 中的动态 RouteConfig