【问题标题】:MVC controller and repository modelMVC 控制器和存储库模型
【发布时间】:2011-10-17 13:46:09
【问题描述】:

我不断收到一条错误消息:

传入字典的模型项的类型为“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); 
        } 
  }

【问题讨论】:

  • 你真的应该在发布更多内容之前开始接受一些答案......

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


【解决方案1】:

您返回的是视图而不是产品中的存储库。改成这样:

var product = repo.GetProductID(id);

return View(product );

【讨论】:

  • 甚至更短的return View(repo.GetProductID(id));
  • @James 甚至更短的return View(new ProductRepository().GetProductID(id)); ;-)
  • @James,甚至更短...return View(new ProductRepository().GetProductID(id)); ...也许我们应该将存储库设为静态以保存另外 3 个字母? ;)
【解决方案2】:

简单,只需传入正确类型的模型/类。如果您确实想传递 ProductRepository 模型,请将您的视图页面的第一行更改为...

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

或者,如果你想传递产品,那么你需要在你的控制器动作中返回它。 (进一步阅读更可能是您正在尝试做的那个)

注意“继承”属性正在设置为您要传递的模型类型。

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

【讨论】:

  • 根据他的 Action 中的代码,我认为他的意图是将产品传递给 View,而不是他的整个存储库。
  • @JustinRusbatch:是的,我在帖子中发表了该评论。无论哪种方式,我想我都解释了为什么会发生错误,这对于纠正他们的代码总是一个有用的补充;)
猜你喜欢
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 2014-08-24
  • 2023-03-20
  • 1970-01-01
  • 2021-07-31
相关资源
最近更新 更多