0

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

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

 <%@ 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); %>

我创建了一个视图模型

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 的错误“对象引用未设置为对象的实例”。

我哪里错了?

4

3 回答 3

5

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

你可以这样做,例如:

ICustomerRepository customerRepository;
IOrderRepository orderRepository;

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

public CustomersController(
    ICustomerRepository customerRepository, 
    IOrderRepository orderRepository)
{
    this.customerRepository = customerRepository;
    this.orderRepository = orderRepository;
}
于 2009-10-09T14:49:03.890 回答
1

嗯,控制器工厂调用了默认控制器,所以调用了这个构造函数:

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

请注意,您只传递了一个 CustomerRepository 对象,而不是一个角色存储库。因此,将您的代码更改为:

ICustomerRepository customerRepository;
IOrderRepository orderRepository;

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

public CustomersController(ICustomerRepository customerRepository, IOrderRepository orderRepository)
{
  this.customerRepository = customerRepository;
  this.orderRepository = orderRepository;
}
于 2009-10-09T14:51:27.847 回答
0

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

于 2009-10-09T14:48:31.117 回答