[英]MVC4: Simplest possible way to get a useful model binding from a string-to-object mapping
I'm in an MVC controller. 我在MVC控制器中。 I have a class, and I would like MVC to treat values of this class in exactly the same way it would treat a Guid
or a DateTime
; 我有一个类,我希望MVC以与对待Guid
或DateTime
完全相同的方式对待此类的值; that is: 那是:
Conceptually, implementing this ought to require only a conversion function for each direction. 从概念上讲,实现此功能仅需要每个方向的转换功能。 Say we have one or more objects implementing this interface: 假设我们有一个或多个实现此接口的对象:
namespace SomeExample
{
public interface SomeStringConversion<T>
{
T ConvertFromString(string str);
string ConvertToString(T obj);
}
}
// Example: What such a class for Guid might look like
namespace SomeExample
{
public class SomeGuidStringConversion : SomeStringConversion<Guid>
{
public Guid ConvertFromString(string str)
{
return Guid.Parse(str);
}
public string ConvertToString(Guid g)
{
return g.ToString();
}
}
}
And say we don't care to validate above and beyond what is accepted or rejected by ConvertFromString()
. 并且说我们不在乎是否超出ConvertFromString()
接受或拒绝的范围进行验证。
What is the straightest path (ie with as little extraneous detail as possible about unrelated features of model binding) from a collection of SomeStringConversion<T>
to a controller that uses them? 从SomeStringConversion<T>
的集合到使用它们的控制器的最直接路径(即,关于模型绑定的不相关功能的尽可能少的多余细节)是什么?
EDIT: I've been a developer for a good while but I'm fresh meat when it comes to MVC. 编辑:我已经有一段时间了,但是在MVC方面我是新鲜的。 I need an example with code from which I can work backwards. 我需要一个示例代码,可以从中进行反向操作。 A high-level description won't be much assistance. 高级别的描述不会有太大帮助。
The most straightfoward way that I can see to implement this would be with a custom model binder. 我可以看到的最简单的方法是使用自定义模型绑定程序。
The binder checks to see if the model type to bind implements the SomeStringConversion<T>
interface and if it does, attempts to bind the model to the incoming string value. 绑定器检查要绑定的模型类型是否实现SomeStringConversion<T>
接口,如果是,则尝试将模型绑定到传入的字符串值。 If it doesn't, it simply defers to DefaultModelBinder
to take the default model binding course of action. 如果没有,它只是顺应DefaultModelBinder
采取默认的模型绑定操作过程。
If the string structure is well-formed you may be able to implement a ValueProvider
to provide the values to a model binder for model binding. 如果字符串结构格式正确,则可以实现ValueProvider
来将值提供给模型绑定器以进行模型绑定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.