在同一页面上渲染两个部分视图

时间:2009-10-09 14:45:22

标签: asp.net-mvc partial-views

我可以显示所有客户的列表,我可以显示所有订单的列表,我想进一步了解。

我想在同一页面上呈现两个部分视图,以显示与该客户相关的客户详细信息和订单。

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage< MyDemo.Models.CustomerAndOrdersViewModel >" %>

<% Html.RenderPartial("CustomerDetails", this.ViewData.Model.Customer); %>
<% Html.RenderPartial("CustomerOrders", this.ViewData.Model.Order); %>

我创建了一个viewmodel

public class CustomerAndOrdersViewModel
{
    public CustomerAndOrdersViewModel(Customer customer,
                        IEnumerable<Order> orders)
    {
        this.Customer = customer;
        this.Order = orders;
    }

    public Customer Customer { get; set; }
    public IEnumerable<Order> Order { get; set; }
}

在我的客户控制器中,我定义了

    ICustomerRepository customerRepository;
    IOrderRepository orderRepository;

    public CustomersController()
        : this(new CustomerRepository())
    {
    }

    public CustomersController(ICustomerRepository repository)
    {
        customerRepository = repository;
    }

    public CustomersController(IOrderRepository repository)
    {
        orderRepository = repository;
    }

然后我尝试将CustomerAndOrdersViewModel传递给详细信息视图

    public ActionResult Details(int id)
    {

        QuestionAndOrderViewModel viewdata = new CustomerAndOrdersViewModel(customerRepository.GetCustomer(id),
                                        orderRepository.FindAllOrders());
        return View(viewdata);
    }

但是我收到的错误是“对象引用未设置为对象的实例”对于orderRepository。

我哪里错了?

3 个答案:

答案 0 :(得分:5)

你的控制器的构造函数只接受一个参数,并且你试图在同一个实例中使用这两个值。

你可以做,例如:

ICustomerRepository customerRepository;
IOrderRepository orderRepository;

public CustomersController()
    : this(new CustomerRepository(), new OrderRepository())
{
}

public CustomersController(
    ICustomerRepository customerRepository, 
    IOrderRepository orderRepository)
{
    this.customerRepository = customerRepository;
    this.orderRepository = orderRepository;
}

答案 1 :(得分:1)

好吧,控制器工厂调用默认控制器,因此调用此构造函数:

public CustomersController() : this(new CustomerRepository())
{
}

请注意,您只传递CustomerRepository对象,而不是rolerepository。所以将代码更改为:

ICustomerRepository customerRepository;
IOrderRepository orderRepository;

public CustomersController() : this(new CustomerRepository(), new OrderRepository())
{}

public CustomersController(ICustomerRepository customerRepository, IOrderRepository orderRepository)
{
  this.customerRepository = customerRepository;
  this.orderRepository = orderRepository;
}

答案 2 :(得分:0)

您在局部视图中遇到错误,因此控制器中的所有代码都无关紧要。您需要查看模型中包含的内容,以及是否将正确的模型传递给局部视图。调试它并在RenderPartial调用中断,然后检查模型,并查看部分视图以查看是否传递了正确的值。