ValueProvider.GetValue 扩展方法
我有一个这样的模型;
public class QuickQuote
{
[Required]
public Enumerations.AUSTRALIA_STATES state { get; set; }
[Required]
public Enumerations.FAMILY_TYPE familyType { get; set; }
正如你所看到的,这两个属性是枚举。
现在我想使用我自己的模型绑定器,因为我现在不想费心去了解。
所以我有;
public class QuickQuoteBinder : DefaultModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
quickQuote = new QuickQuote();
try
{
quickQuote.state = (Enumerations.AUSTRALIA_STATES)
Enum.Parse(typeof(Enumerations.AUSTRALIA_STATES),
bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".state").AttemptedValue);
}
catch {
ModelState modelState = new ModelState();
ModelError err = new ModelError("Required");
modelState.Errors.Add(err);
bindingContext.ModelState.Add(bindingContext.ModelName + ".state", modelState);
}
问题是,对于每个属性,并且有堆,我需要执行整个 try catch 块。
我想我可能会做的是创建一个扩展方法,它可以为我完成整个块,我需要传入的是模型属性和枚举。
所以我可以做类似的事情;
quickQuote.state = bindingContext.ValueProvider.GetModelValue("state", ...)
等。
这可能吗?
I have a model like this;
public class QuickQuote
{
[Required]
public Enumerations.AUSTRALIA_STATES state { get; set; }
[Required]
public Enumerations.FAMILY_TYPE familyType { get; set; }
As you can see the two proerties are enumerations.
Now I want to employ my own model binder for reasons that I won't bother getting into at the moment.
So I have;
public class QuickQuoteBinder : DefaultModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
quickQuote = new QuickQuote();
try
{
quickQuote.state = (Enumerations.AUSTRALIA_STATES)
Enum.Parse(typeof(Enumerations.AUSTRALIA_STATES),
bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".state").AttemptedValue);
}
catch {
ModelState modelState = new ModelState();
ModelError err = new ModelError("Required");
modelState.Errors.Add(err);
bindingContext.ModelState.Add(bindingContext.ModelName + ".state", modelState);
}
The problem is that for each property, and there are heaps, I need to do the whole try catch block.
What I thought I might do is create an extension method which would do the whole block for me and all i'd need to pass in is the model property and the enumeration.
So I could do something like;
quickQuote.state = bindingContext.ValueProvider.GetModelValue("state", ...)
etc.
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你可以有一个扩展方法。这是一个非常简单的示例,展示了如何编写它。
我要考虑的另一件事是使用 Enum.IsDefined 而不是 try catch 块。它将提高性能并可能产生更具可读性的代码。
Yes you can have an extension method. Here's a very simple example to show how you'd write it.
The other thing I'd consider is to use Enum.IsDefined rather than a try catch block. It will improve performance and probably result in more readable code.
好的,我明白了。
's ok, I got it.