Object as a parameter for an action controller?

前端 未结 3 425
走了就别回头了
走了就别回头了 2021-01-28 09:21

Is it possible for an action controller to accept a literal object. For example, I have several views in which I would like to post various models from to a single controller th

3条回答
  •  猫巷女王i
    2021-01-28 10:05

    The Default Asp.NET ModelBinder cannot bind generic Objects this way. You should take a look here to understand how the model will be build back in the server by the DefaultModelBinder: Understanding ASP.NET MVC Model Binding.

    Given that your form has many Models, you should encapsulate them into a ViewModel to do this kind of operation.

    The ViewModel should looks like this:

    public class MyViewModel
    {
      public Model1 Model1 {get; set;}
      public Model1 Model2 {get; set;}
      public Model1 Model3 {get; set;}
    }
    

    And the controller:

    [HttpPost]
    public ActionResult ProcessModel(MyViewModel myViewModel)
    {
      // determine the model
      if(myViewModel.Model1 != null)
      {
        // continue with code
      }
      else if(myViewModel.Model2 != null)
      {
        // continue with code
      }
      // continue with model check, etc.       
    }
    

提交回复
热议问题