简体   繁体   中英

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...
  }
}

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

您可以在视图中使用Tuple <>来拥有两个视图模型,然后在每种表单的@ Html.BeginForm()帮助器方法中,可以将POST指定给两个不同的控制器来处理表单数据。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM