如果我在模型中使用不可变结构,即:
public struct ImmutableStruct
{
private readonly int firstProperty;
public ImmutableStruct(int firstProperty) : this()
{
this.firstProperty = firstProperty
}
public int FirstProperty { get { return firstProperty; } }
}
模型片段:
public class SomeModel
{
public ImmutableStruct structProperty { get; set; }
}
视图片段:
@model SomeModel
<div>
@Html.EditorFor(x = x.structProperty.FirstProperty)
</div>
在回发到控制器时,模型绑定器似乎无法绑定任何数据。这是否意味着(1)不应使用不可变结构,(2)需要使用自定义模型绑定器,(3)或者我需要做其他事情呢?
答案 0 :(得分:3)
据我所知,MVC需要一个默认的无参数构造函数。您的构造函数不符合条件,因为它需要一个参数。 MVC通过属性进行绑定,并且您的属性没有setter。
我相信自定义模型绑定器可以解决您的问题,允许您调用构造函数。看起来比它值得多麻烦,特别是因为你可能必须在你的类中添加属性时修改你的自定义模型绑定器。但我会由你决定。
此模型绑定器中举例说明了如何对参数化构造函数进行模型绑定的详细信息:
https://stackoverflow.com/a/13535545/84206
注意return new Company(customProfile);
与new ImmutableStruct(someValue)