title: Passing an interface to an ASP.NET MVC Controller Action method
body: <p>In my ASP.NET MVC app, I have an interface which acts as the template for several different view models:</p>
  
  <pre><code>public interface IMyViewModel
  {
      Client Client1 { get; set; }
      Client Client2 { get; set; }
  
      Validator Validate();
  }
  </code></pre>
  
  <p>So, my view models are defined like this:</p>
  
  <pre><code>public interface MyViewModel1 : IMyViewModel
  {
      Client Client1 { get; set; }
      Client Client2 { get; set; }
  
      // Properties specific to MyViewModel1 here
  
      public Validator Validate()
      {
          // Do ViewModel-specific validation here
      }
  }
  
  public interface MyViewModel2 : IMyViewModel
  {
      Client Client1 { get; set; }
      Client Client2 { get; set; }
  
      // Properties specific to MyViewModel2 here
  
      public Validator Validate()
      {
          // Do ViewModel-specific validation here
      }
  }
  </code></pre>
  
  <p>Then I currently have a separate controller action to do the validation for each different type, using model binding:</p>
  
  <pre><code>[HttpPost]
  public ActionResult MyViewModel1Validator(MyViewModel1 model)
  {
      var validator = model.Validate();
  
      var output = from Error e in validator.Errors
                   select new { Field = e.FieldName, Message = e.Message };
  
      return Json(output);
  }
  
  [HttpPost]
  public ActionResult MyViewModel2Validator(MyViewModel2 model)
  {
      var validator = model.Validate();
  
      var output = from Error e in validator.Errors
                   select new { Field = e.FieldName, Message = e.Message };
  
      return Json(output);
  }
  </code></pre>
  
  <p>This works fine—but if I had 30 different view model types then there would have to be 30 separate controller actions, all with <em>identical</em> code apart from the method signature, which seems like bad practice.</p>
  
  <p>My question is, how can I consolidate these validation actions so that I can pass any kind of view model in and call it's Validate() method, without caring about which type it is?</p>
  
  <p>At first I tried using the interface itself as the action parameter:</p>
  
  <pre><code>public ActionResult MyViewModelValidator(IMyViewModel model)...
  </code></pre>
  
  <p>But this didn't work: I get a <code>Cannot create an instance of an interface</code> exception. I thought an instance of the model would be passed into the controller action, but apparently this is not the case.</p>
  
  <p>I'm sure I'm missing something simple. Or perhaps I've just approached this all wrong. Can anyone help me out?</p>