开发者

MVC controller and repository model

I keep getting an error saying that:

The model item passed into the dictionary is of type 'HomebaseSystemNew.Controllers.ProductRepository', but this dictionary requires a model item of type 'HomebaseSystemNew.Models.Product'

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

My Repository:

  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);
    }
    }

My Controller:

using System.Linq;

using System.Web.Mvc;

using HomebaseSystemNew.Models;


namespace HomebaseSystemNew.Controllers
  {

    public class ProductsController : Controller
 {

       public ActionResult EditProduct(int id)  
       {
             ProductReposito开发者_JAVA百科ry repo = new ProductRepository();

             repo.GetProductID(id);

             return View(repo); 
        } 
  }


You are returning the repository in the View not the Product. Change it to this:

var product = repo.GetProductID(id);

return View(product );


Easy one, just pass in the right type of Model/Class. If you definitely want to pass a ProductRepository Model then change the first line of your View page to be...

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

Alternatively, if you want to pass the Product, then you need to return that in your controller action. (Which on further reading is more likely the one you are trying to do)

Notice the "Inherits" property is being set with the model type that you want to pass.

Also note that you do not typically want to put repositories in your controller folder - best to keep that for just controller classes ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜