开发者

asp.net mvc 2 - Model Binding and Select Lists

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).


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜