模型绑定自定义类型
我有一个结构,其工作方式与 System.Nullable 类型非常相似:
public struct SpecialProperty<T>
{
public static implicit operator T(SpecialProperty<T> value)
{
return value.Value;
}
public static implicit operator SpecialProperty<T>(T value)
{
return new SpecialProperty<T> { Value = value };
}
T internalValue;
public T Value { get { return internalValue; } set { internalValue = value; } }
public override bool Equals(object other)
{
return Value.Equals(other);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return Value.ToString();
}
}
我尝试将它与 ASP.NET MVC 绑定一起使用。使用默认的客户模型绑定器,该属性将始终产生 null。我可以通过在每个表单输入名称的末尾添加“.Value”来解决这个问题,但我只是希望它使用某种自定义模型绑定器直接绑定到新类型,但我尝试过的所有解决方案似乎都不必要地复杂。我觉得我应该能够扩展默认绑定器,并使用几行代码使用隐式转换将属性绑定重定向到整个模型。我不太了解默认绑定器的绑定范例,但它似乎确实停留在模型和模型属性之间的区别上。做到这一点最简单的方法是什么? 谢谢!
I have a struct which works much like the System.Nullable type:
public struct SpecialProperty<T>
{
public static implicit operator T(SpecialProperty<T> value)
{
return value.Value;
}
public static implicit operator SpecialProperty<T>(T value)
{
return new SpecialProperty<T> { Value = value };
}
T internalValue;
public T Value { get { return internalValue; } set { internalValue = value; } }
public override bool Equals(object other)
{
return Value.Equals(other);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public override string ToString()
{
return Value.ToString();
}
}
I'm trying to use it with ASP.NET MVC binding. Using the default customer model binder the property will always yield null. I can fix this by adding ".Value" to the end of every form input name, but I just want it to bind to the new type directly using some sort of custom model binder, but all the solutions I've tried seemed needlessly complex. I feel like I should be able to extend the default binder and with a few lines of code redirect the property binding to the entire model using implicit conversion. I don't quite get the binding paradigm of the default binder, but it seems really stuck on this distinction between the model and model properties. What is the simplest method to do this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
找到了答案。我只需要实现一个自定义类型转换器,默认模型绑定器就会选择它。
Found the answer. I just needed to implement a custom type converter and the default model binder picked it up.