Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 819783
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T02:22:02+00:00 2026-05-15T02:22:02+00:00

Is it possible to bind a foreign key relationship on my model to a

  • 0

Is it possible to bind a foreign key relationship on my model to a form input?

Say I have a one-to-many relationship between Car and Manufacturer. I want to have a form for updating Car that includes a select input for setting Manufacturer. I was hoping to be able to do this using the built-in model binding, but I’m starting to think I’ll have to do it myself.

My action method signature looks like this:

public JsonResult Save(int id, [Bind(Include="Name, Description, Manufacturer")]Car car)

The form posts the values Name, Description and Manufacturer, where Manufacturer is a primary key of type int. Name and Description get set properly, but not Manufacturer, which makes sense since the model binder has no idea what the PK field is. Does that mean I would have to write a custom IModelBinder that it aware of this? I’m not sure how that would work since my data access repositories are loaded through an IoC container on each Controller constructor.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T02:22:03+00:00Added an answer on May 15, 2026 at 2:22 am

    Here’s my take – this is a custom model binder that when asked to GetPropertyValue, looks to see if the property is an object from my model assembly, and has a IRepository<> registered in my NInject IKernel. If it can get the IRepository from Ninject, it uses that to retrieve the foreign key object.

    public class ForeignKeyModelBinder : System.Web.Mvc.DefaultModelBinder
    {
        private IKernel serviceLocator;
    
        public ForeignKeyModelBinder( IKernel serviceLocator )
        {
            Check.Require( serviceLocator, "IKernel is required" );
            this.serviceLocator = serviceLocator;
        }
    
        /// <summary>
        /// if the property type being asked for has a IRepository registered in the service locator,
        /// use that to retrieve the instance.  if not, use the default behavior.
        /// </summary>
        protected override object GetPropertyValue( ControllerContext controllerContext, ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder )
        {
            var submittedValue = bindingContext.ValueProvider.GetValue( bindingContext.ModelName );
            if ( submittedValue == null )
            {
                string fullPropertyKey = CreateSubPropertyName( bindingContext.ModelName, "Id" );
                submittedValue = bindingContext.ValueProvider.GetValue( fullPropertyKey );
            }
    
            if ( submittedValue != null )
            {
                var value = TryGetFromRepository( submittedValue.AttemptedValue, propertyDescriptor.PropertyType );
    
                if ( value != null )
                    return value;
            }
    
            return base.GetPropertyValue( controllerContext, bindingContext, propertyDescriptor, propertyBinder );
        }
    
        protected override object CreateModel( ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType )
        {
            string fullPropertyKey = CreateSubPropertyName( bindingContext.ModelName, "Id" );
            var submittedValue = bindingContext.ValueProvider.GetValue( fullPropertyKey );
            if ( submittedValue != null )
            {
                var value = TryGetFromRepository( submittedValue.AttemptedValue, modelType );
    
                if ( value != null )
                    return value;
            }
    
            return base.CreateModel( controllerContext, bindingContext, modelType );
        }
    
        private object TryGetFromRepository( string key, Type propertyType )
        {
            if ( CheckRepository( propertyType ) && !string.IsNullOrEmpty( key ) )
            {
                Type genericRepositoryType = typeof( IRepository<> );
                Type specificRepositoryType = genericRepositoryType.MakeGenericType( propertyType );
    
                var repository = serviceLocator.TryGet( specificRepositoryType );
                int id = 0;
    #if DEBUG
                Check.Require( repository, "{0} is not available for use in binding".FormatWith( specificRepositoryType.FullName ) );
    #endif
                if ( repository != null && Int32.TryParse( key, out id ) )
                {
                    return repository.InvokeMethod( "GetById", id );
                }
            }
    
            return null;
        }
    
        /// <summary>
        /// perform simple check to see if we should even bother looking for a repository
        /// </summary>
        private bool CheckRepository( Type propertyType )
        {
            return propertyType.HasInterface<IModelObject>();
        }
    
    }
    

    you could obviously substitute Ninject for your DI container and your own repository type.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is it possible to bind the multiple commands to the button. I have a
Is it possible to bind an additional resource string to another attribute within a
Does anyone know if it is possible (and if yes, how) to bind an
In WPF, is it possible for a DataTrigger to bind to an attached property?
Possible Duplicate: NAnt or MSBuild, which one to choose and when? What is the
Possible Duplicate: How does the Google Did you mean? Algorithm work? Suppose you have
Is it possible to bind the alpha value of an element to a slider?
Is it possible to bind to a property of a property? Here is what
Is it possible to bind something to a property of a control in a
Is it possible to bind such kind of property? public KeyValuePair<string, string> Stuff {

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.