ValueProvider.GetValue Extension Method
- by griegs
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?