poy
poy

Reputation: 10507

Posting with multiple models in a view

So I have a View that contains 2 models. Each model has its own form and submit button.

Currently, I have both submit buttons are processed by the same controller method and use reflection to figure out which model type was passed. But it seems like there would be a better way... any ideas?

I have something like this:

Models:

public class Model1
{
  // Elements
}

public class Model2
{
  // Elements
}

Controller:

public ViewResult ConMeth(Object model)
{
  Type t = model.GetType();
  if(t == typeof(Model1)
  {
    // Do work for Model1
  }
  else if(t == typeof(Model2)
  {
    // Do work for Model2
  }
  else
  {
    // Do something else...
  }
}

Upvotes: 1

Views: 103

Answers (2)

A Biz
A Biz

Reputation: 37

You can use a Tuple<> in your view to have two view models, and then in the @Html.BeginForm() helper method for each form, you can specify POSTs to two different controllers to process your form data.

@model Tuple<ProjectName.Models.Model1, ProjectName.Models.Model2>

Upvotes: 0

Rikon
Rikon

Reputation: 2696

If you show your view info, I suspect you've got two seperate things happening in the view. Just put each thing in it's own form and use the

@using (Html.BeginForm(...)){}

and specify the actions by name and the controller (if necessary) in the BeginForm params... That should get rid of the ambiguous reference error

Here is an example w/ the older (not razor) tags

Upvotes: 1

Related Questions