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 3605268
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T21:06:08+00:00 2026-05-18T21:06:08+00:00

I have an IIdentifiable interface: public interface IIdentifiable { int Id { get; set;

  • 0

I have an IIdentifiable interface:

public interface IIdentifiable
{
    int Id { get; set; }
}

And a simple class Foo:

public class Foo : IIdentifiable
{
    public int Id { get; set; }
    public string Name { get; set; }
}

When I have a page that needs to add a set of Foo and the specify one as the default, I’d have a view model like this:

public class BarViewModel
{
    public IList<Foo> Foos { get; set; }
    public Foo DefaultFoo { get; set; }
}

So in reality I’d like to only pass the Ids around and not the actual full objects inside hidden inputs (that’s just nasty and not required). All bar cares about (int the database at least) is between a Bar and it’s Foo.Ids and the default Foo.Id.

I was hoping to easily add a model binder that would be able to accept all IIdentifiables and then set the Id if only an int is set for the value provider. The problem that I ran into is that I can’t do something like the following and have it set the Id (since model binders don’t look at the derived type chain…ugh):

ModelBinders.Binders[typeof(IIdentifiable)] = new IdentifiableModelBinder();

So I decided to extend the DefaultModelProvider to allow this capability for if the type is an IIdentifiable and the value found in the value provider is just a string/int, then create the model and set the Id property to the matching value:

public class DefaultWithIdentifiableModelBinder : DefaultModelBinder
{

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        var modelType = bindingContext.ModelType;
        bool isList = false;

        // Determine the real type of the array or another generic type.
        if (modelType.IsArray)
        {
            modelType = modelType.GetElementType();
            isList = true;
        }
        else if (modelType.IsGenericType)
        {
            var genericType = modelType.GetGenericTypeDefinition();

            if (genericType == typeof(IEnumerable<>) || genericType == typeof(IList<>) || genericType == typeof(ICollection<>))
            {
                modelType = modelType.GetGenericArguments()[0];
                isList = true;
            }
        }

        // The real model type isn't identifiable so use the default binder.
        if (!typeof(IIdentifiable).IsAssignableFrom(modelType))
        {
            return base.BindModel(controllerContext, bindingContext);
        }

        // Get the value provider for the model name.
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        // Get the string values from the value provider.
        var stringValues = valueProviderResult != null ? (IEnumerable<string>)valueProviderResult.RawValue : Enumerable.Empty<string>();

        int tempFirstId = -1;

        // If the first element is an integer, we assume that only the Ids are supplied
        // and therefore we parse the list.
        // Otherwise, use the default binder.
        if (stringValues.Any() && int.TryParse(stringValues.First(), out tempFirstId))
        {

            var listType = typeof(List<>).MakeGenericType(new Type[] { modelType });

            var items = (IList)base.CreateModel(controllerContext, bindingContext, listType);

            // Create each identifiable object and set the Id.
            foreach (var id in stringValues)
            {
                var item = (IIdentifiable)Activator.CreateInstance(modelType);
                item.Id = int.Parse(id);
                items.Add(item);
            }

            if (items.Count == 0)
            {
                return null;
            }

            // Determine the correct result to return.
            if (bindingContext.ModelType.IsArray)
            {
                var array = Array.CreateInstance(modelType, items.Count);
                items.CopyTo(array, 0);
                return array;
            }
            else if (isList)
            {
                return items;
            }
            else
            {
                return items[0];
            }
        }
        else
        {
            return base.BindModel(controllerContext, bindingContext);
        }

    }

}

I’m just not sure if this is really necessary for what I’m trying to do. If anyone could leave feedback/suggestions/improvements on this type of model binding it would be greatly appreciated.

EDIT: Here’s a simple example:

An order has many items, so instead of loading the whole object graph of the Item, only the Id is really required for use with the ORM and in the database. Therefore, the item class is loaded with the Id and then the item can be added to the list of items for the order:

public class Order
{
    List<Item> Items { get; set; }
}

var order = new Order();
order.Items.Add(new Item() { Id=2 });
order.Items.Add(new Item() { Id=5 });

This is because the postback to complete the order doesn’t send the whole Item, it just sends the Ids.

This is my core requirement. When a postback occurs, I need to build the Items from an Id from the postback. Regardless of if this is a view model or the actual domain model, I still need a way of easily converting from ints to the domain model with the Id set. Make sense?

  • 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-18T21:06:09+00:00Added an answer on May 18, 2026 at 9:06 pm

    This seems like a decent way but not very extensible. If you’re unlikely to have this same situation arise with different interfaces, then it’s a fine solution.

    An alternative would be to use reflection at startup to find all types that implement IIdentifiable and assign the custom model binder for all of them.

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

Sidebar

Related Questions

Have you managed to get Aptana Studio debugging to work? I tried following this,
Have just started using Google Chrome , and noticed in parts of our site,
Have you ever seen any of there error messages? -- SQL Server 2000 Could
Have you guys had any experiences (positive or negative) by placing your source code/solution
Have just started using Visual Studio Professional's built-in unit testing features, which as I
Have you used VS.NET Architect Edition's Application and System diagrams to start designing a
Have you determined a maximum number of characters allowed in FCKEditor ? I seem
Have a n-tire web application and search often times out after 30 secs. How
Have had to write my first proper multithreaded coded recently, and realised just how
Have you refactored from an ActiveRecord to a DataMapper pattern? What conditions prompted the

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.