MVC控制器和存储库模型

use*_*239 1 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>" %>
Run Code Online (Sandbox Code Playgroud)

我的存储库:

  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);
    }
    }
Run Code Online (Sandbox Code Playgroud)

我的控制器:

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); 
        } 
  }
Run Code Online (Sandbox Code Playgroud)

And*_*ose 6

您将在"视图而不是产品"中返回存储库.把它改成这个:

var product = repo.GetProductID(id);

return View(product );
Run Code Online (Sandbox Code Playgroud)

  • @James,甚至更短...`return View(new ProductRepository().GetProductID(id));`...也许我们应该使存储库静态以保存另外3个字母?;) (2认同)