In my models I have a BIGINT (long/int64) foreign key reference to LookupCategory. In the View, I have a DropDownListFor as follows:
@Html.DropDownListFor(model => model.LookupKey.LookupCategory, new SelectList(Model.LookupCategories, "ID", "Name"))
The create/edit views display fine, but upon selecting an item submitting the ModelBinder complains “The value '1' is invalid.” because it is reading it in as a string rather than a long.
Is there a way to fix this without touching the model? I’d prefer not to implement ModelBinder just to solve this little issue, but if I must, I’ve got this drafted:
public class LookupKeyBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
if (propertyDescriptor.PropertyType == typeof(LookupKey))
{
var modelState = bindingContext.ModelState[string.Format("{0}.{1}", propertyDescriptor.Name, "LookupCategory")];
propertyDescriptor.SetValue(bindingContext.Model, long.Parse(modelState.Value.AttemptedValue));
modelState.Errors.Clear();
return;
}
}
}
It’s arranged like that because I want access to the ModelState, not have to know the form field names (which could change between views). So I get the long value properly, but the problem is that the DefaultModelBinder already did its work and instead of long, I need the actual LookupCategory (whose ID is the long value). I can’t figure out how to use the default model binder again to use its default behavior for finding the LookupCategory from the database. Anyway, this is a lot of trickery for something that seems like it should be simple!
As I suspected, examining the model and LookupKey classes helped resolve the issue. I have had several experiences like that, where a second look at the class showed I was not using the correct model property.
When you changed your DropDownListFor to use
model.LookupKey.LookupCategory.ID, that synced up with the correct property, and viola!Congrats on spotting the problem.