15

我有一个控制器动作,其定义看起来像 -

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
}

在控制器操作中填充了“名称”属性,但SourceId属性仍然为空。哪个destinationId是长的参数也被填充。

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

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

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

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"}
4

3 回答 3

4

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

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

这适用于我的情况(Int32 -> decimal?,ASP NET MVC 3)

于 2011-10-18T05:22:57.987 回答
2

我建议您在视图模型上使用属性而不是字段:

public class MyModel
{
    public string Name { get; set; }
    public long? SourceId { get; set; }
}

现在提出以下要求:

/somecontroller/changemodel?destinationId=123&info[0].Name=name1&info[0].SourceId=1&info[1].Name=name2&info[1].SourceId=2

很好地填充模型。

于 2011-05-02T19:04:42.593 回答
1

默认模型绑定器将所有值解析SourceId为整数。但似乎 .NET 缺少从intto的默认类型转换器long?

我要做的是为这种情况实现一个类型转换器

于 2011-05-02T13:35:28.047 回答