我有一个 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/