2

I have the following select list:

<select d="Owner_Id" name="Owner.Id">
    <option value="">[Select Owner]</option>
    <option value="1">Owner 1</option>
    <option value="2">Owner 2</option>
    <option value="3">Owner 3</option>
</select>

It gets bound to:

public class Part
{
    // ...other part properties...
    public Owner Owner {get; set;}
}

public class Owner
{
    public int Id {get; set;}
    public string Name {get; set;}
}

The problem I'm running into is that if the [Select Owner] option is selected then an error is thrown because I'm binding an empty string to an int. The behavior I want is an empty string just results in a null Owner property on Part.

Is there a way to modify the Part model binder to get this behavior? So when binding the Owner property of Part, if Owner.Id is an empty string then just return a null Owner. I can't modify the Owner model binder as I require the default behavior in its own controller (adding/removing Owners).

1 Answer 1

1

You could try a custom model binder:

public class PartBinder : DefaultModelBinder
{
    protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
    {
        if (propertyDescriptor.PropertyType == typeof(Owner))
        {
            var idResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName + ".Id");
            if (idResult == null || string.IsNullOrEmpty(idResult.AttemptedValue))
            {
                return null;
            }
        }
        return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
    }
}

And then:

[HttpPost]
public ActionResult Index([ModelBinder(typeof(PartBinder))]Part part)
{
    return View();
}

or register it globally:

ModelBinders.Binders.Add(typeof(Part), new PartBinder());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.