MVC控制器和存储库模型

时间:2011-10-17 13:46:10

标签: c# asp.net-mvc-3

我一直在说错误:

传递到字典中的模型项的类型为“HomebaseSystemNew.Controllers.ProductRepository”,但此字典需要“HomebaseSystemNew.Models.Product”类型的模型项

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

我的存储库:

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using HomebaseSystemNew.Models;

  namespace HomebaseSystemNew.Controllers
  {
     public class ProductRepository
   {

  public Product GetProductID(int Pid)
    {
        DatabaseLinkedDataContext db = new DatabaseLinkedDataContext();

        return db.Products.FirstOrDefault(ans => ans.Pid == Pid);
    }
    }

我的控制器:

using System.Linq;

using System.Web.Mvc;

using HomebaseSystemNew.Models;


namespace HomebaseSystemNew.Controllers
  {

    public class ProductsController : Controller
 {

       public ActionResult EditProduct(int id)  
       {
             ProductRepository repo = new ProductRepository();

             repo.GetProductID(id);

             return View(repo); 
        } 
  }

2 个答案:

答案 0 :(得分:6)

您将在View not the Product中返回存储库。将其更改为:

var product = repo.GetProductID(id);

return View(product );

答案 1 :(得分:1)

简单一点,只需传递正确类型的模型/类。如果您肯定想要传递ProductRepository模型,请将View页面的第一行更改为...

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

或者,如果要传递产品,则需要在控制器操作中返回该产品。 (进一步阅读哪一个更有可能是你想要做的那个)

请注意,正在使用您要传递的模型类型设置“Inherits”属性。

另请注意,您通常不希望将存储库放在控制器文件夹中 - 最好只保留控制器类;)

相关问题