ASP.NET MVC:如何在一个视图中使用多个模型? [英] ASP.NET MVC: How to use multiple models in one View?

查看:72
本文介绍了ASP.NET MVC:如何在一个视图中使用多个模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下包含2个其他模型的ViewModel:

I have the following ViewModel that includes 2 other models:

public class ViewModel
{
   public ViewModel1 viewModel1 { get; set; }
   public ViewModel2 viewModel2 { get; set; }
}

我的视图如下:

@Html.TextBoxFor(m => m.viewModel1.NameOfCustomer)
@Html.TextBoxFor(m => m.viewModel2.ProductCategory)

最后是控制器:

public ActionResult CreateNewOrder(ViewModel viewModel)
{

  Model1 myModel1 = new Model1()
  {
    NameOfCustomer = viewModel.viewModel1.NameOfCustomer
  };

  db.Orders.Add(myModel1);
  db.SaveChanges();

  return View(viewModel);
}

问题是,如果我想从ViewModel中获取数据以将其传递给我的实际模型,它将无法正常工作.它只是将null显示为值.如果我对控制器数据进行了以下更改,但是它不起作用,应该这样做:

The problem is, if I want to take the data from my ViewModel to pass it to my actual model, it does not work. It just shows null as value. If I do the following change to my controller data is there but this does not work as it should:

public ActionResult CreateNewOrder(ViewModel viewModel)
{
  // that works
  viewModel.viewModel1.NameOfCustomer = "John John";

  Model1 myModel1 = new Model1()
  {
    myModel1.NameOfCustomer = viewModel.viewModel1.NameOfCustomer
  };

  db.Orders.Add(myModel1);
  db.SaveChanges();

  return View(viewModel);
}

所以我想问题是,我的视图中的数据没有正确发送到ViewModel.我希望你们能给我一个提示,我在做什么错了.

So I guess the problem is, my data from my view is not being send correctly to my ViewModel. I hope you guys can give me a hint what Im doing wrong.

此致

推荐答案

您的代码应正确地将信息传递给控制器​​(请参见类似的提琴

Your code should properly carry the information to the controller(see a similar fiddle here)

作品:

Model1 myModel1 = new Model1()
  {
    NameOfCustomer = viewModel.viewModel1.NameOfCustomer
  };

  db.Orders.Add(myModel1);
  db.SaveChanges();

您确定在这里做对了吗?您正在创建一个 Model1 类型变量,并将其添加到数据库中的 Orders 中.您有任何错误吗?也许正确的代码应该是这样的:

Are you sure you are doing the right thing here? You are creating a Model1 type variable and add it to the Orders in your database. Are you getting any errors? Maybe the right code should be something like:

      Order myModel1 = new Order ()
      {
        NameOfCustomer = viewModel.viewModel1.NameOfCustomer
      };

      db.Orders.Add(myModel1);
      db.SaveChanges();

这篇关于ASP.NET MVC:如何在一个视图中使用多个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆