Asp. NET MVC Продукт> ПродуктФото - PullRequest
0 голосов
/ 10 марта 2020

У меня есть две отдельные таблицы продуктов и фотографий продуктов

Когда я проверяю какие-либо детали в таблице продуктов, я хочу, чтобы фотографии этого продукта появлялись. В этом случае я помещаю его в таблицу сведений в поле с именем _UrunFotoPartitialView как @ html .partitial (""), но всегда

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Urun_C7B3883A1159F8EE0177C29B1CA535182B157B3C5BB798ABCC8C2A72FB5CFED9', but this dictionary requires a model item of type 'Tututuncu.Models.UrunFotoViewModel'.

выдает ошибку. Сколько дней я имел дело, но я не мог это сделать.

Класс Уруна

 public partial class Urun
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Urun()
    {
        this.Firma = new HashSet<Firma>();
        this.Musteri = new HashSet<Musteri>();
        this.Satis = new HashSet<Satis>();
    }

    public int UrunID { get; set; }
    public Nullable<int> UrunFotoID { get; set; }
    public Nullable<int> MarkaID { get; set; }
    public string UrunAdi { get; set; }
    public Nullable<decimal> UrunFiyat { get; set; }
    public Nullable<decimal> UrunAlisFiyat { get; set; }
    public Nullable<int> UrunStok { get; set; }
    public string UrunAciklama { get; set; }
    public Nullable<System.DateTime> UretimYili { get; set; }
    public Nullable<System.DateTime> EklenmeTarihi { get; set; }
    public Nullable<System.DateTime> GuncellenmeTarihi { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Firma> Firma { get; set; }
    public virtual Markalar Markalar { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Musteri> Musteri { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Satis> Satis { get; set; }
    public virtual UrunFoto UrunFoto { get; set; }
}

Класс Уруна Фото

public partial class UrunFoto
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public UrunFoto()
    {
        this.Urun = new HashSet<Urun>();
    }

    public int FotoID { get; set; }
    public Nullable<int> UrunFotoID { get; set; }
    public string BuyukYol { get; set; }
    public string OrtaYol { get; set; }
    public string KucukYol { get; set; }
    public Nullable<bool> Varsayilan { get; set; }
    public string SiraNo { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Urun> Urun { get; set; }
}

Мой UrunController

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tututuncu.Models;

namespace Tututuncu.Areas.Yonetim.Controllers
{
    [Authorize]
    public class UrunController : Controller
    {
        private StokDBEntities db = new StokDBEntities();

        // GET: Yonetim/Urun
        public ActionResult Index()
        {
            return RedirectToAction("Listele");
        }

        public ActionResult Listele()
        {
            var urun = db.Urun.Include(u => u.Markalar).Include(u => u.UrunFoto);
            return View(urun.ToList());
        }


        public ActionResult Yeni()
        {
            ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd");
            ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Yeni([Bind(Include = "UrunID,UrunFotoID,MarkaID,UrunAdi,UrunFiyat,UrunAlisFiyat,UrunStok,UrunAciklama,UretimYili,EklenmeTarihi,GuncellenmeTarihi")] Urun urun)
        {
            if (ModelState.IsValid)
            {
                db.Urun.Add(urun);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
            ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
            return View(urun);
        }


        public ActionResult Guncelle(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Urun urun = db.Urun.Find(id);
            if (urun == null)
            {
                return HttpNotFound();
            }
            ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
            ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
            return View(urun);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Guncelle([Bind(Include = "UrunID,UrunFotoID,MarkaID,UrunAdi,UrunFiyat,UrunAlisFiyat,UrunStok,UrunAciklama,UretimYili,EklenmeTarihi,GuncellenmeTarihi")] Urun urun)
        {
            if (ModelState.IsValid)
            {
                db.Entry(urun).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
            ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
            return View(urun);
        }

        public ActionResult Sil(int id)
        {
            var silinecekUrun = db.Urun.Find(id);
            if (silinecekUrun == null)
                return HttpNotFound();
            db.Urun.Remove(silinecekUrun);
            db.SaveChanges();
            return RedirectToAction("Index", "Urun");
        }



        public ActionResult UrunResimEkle(int id)
        {
            Urun urun = db.Urun.Find(id);
            ViewBag.Foto = urun;
            return View(urun);
        }

        public ActionResult FotoListele(int id)
        {
            Urun urun = db.Urun.Find(id);
            ViewBag.Foto = urun;
            return View(urun);
        }

        [HttpPost]
        public ActionResult UrunResimEkle(int uId, HttpPostedFileBase fileUpload)
        {

            if (fileUpload != null)
            {
                Image img = Image.FromStream(fileUpload.InputStream);

                Bitmap kucukResim = new Bitmap(img, ResimAyar.UrunKucukBoyut);
                Bitmap ortaResim = new Bitmap(img, ResimAyar.UrunOrtaBoyut);
                Bitmap buyukResim = new Bitmap(img, ResimAyar.UrunBuyukBoyut);
                string buyukYol = "/images/UrunFoto/Buyuk/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
                string ortaYol = "/images/UrunFoto/Orta/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
                string kucukYol = "/images/UrunFoto/Kucuk/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);

                kucukResim.Save(Server.MapPath(kucukYol));
                ortaResim.Save(Server.MapPath(ortaYol));
                buyukResim.Save(Server.MapPath(buyukYol));

                UrunFoto rsm = new UrunFoto();
                rsm.BuyukYol = buyukYol;
                rsm.OrtaYol = ortaYol;
                rsm.KucukYol = kucukYol;
                rsm.UrunFotoID = uId;
                if (db.UrunFoto.FirstOrDefault(x => x.UrunFotoID == uId && x.Varsayilan == false) != null)
                    rsm.Varsayilan = true;
                else
                    rsm.Varsayilan = false;
                db.UrunFoto.Add(rsm);
                db.SaveChanges();
                return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
            }
            return View(uId);

        }



        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Страница просмотра Urun

@model IEnumerable<Tututuncu.Models.Urun>

@{
    ViewBag.Title = "Ürüne Resim Ekle";
    Layout = "~/Areas/Yonetim/Views/Shared/_Layout.cshtml";
}


<!-- Page Content -->
<div id="page-wrapper">
    <div class="container-fluid">
        <div class="row bg-title">
            <div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
                <h4 class="page-title">File Upload</h4>
            </div>
            <div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
                <ol class="breadcrumb">
                    <li><a href="/Default.aspx">Yönetim Paneli</a></li>
                    <li class="active">File Upload</li>
                </ol>
            </div>
            <!-- /.col-lg-12 -->
        </div>
        <!-- .row -->


        <div class="row">
            <div class="col-sm-12 ol-md-6 col-xs-12">
                <div class="white-box">
                    <h3 class="box-title">File Upload1</h3>
                    <label for="input-file-now">Your so fresh input file — Default version</label>
                    <form action="/Yonetim/Urun/UrunResimEkle" method="post" enctype="multipart/form-data">
                        <input type="hidden" name="uId" value="@Model" />


                        <input type="file" name="fileUpload" />
                        <input type="submit" name="name" value="Kaydet" class="btn btn-primary" />

                    </form>
                </div>
            </div>
        </div>


           @Html.Partial("FotoListele")

    </div>
</div>

Моя страница просмотра партитуры

@model IEnumerable<Tututuncu.Models.UrunFoto>

@{
    ViewBag.Title = "FotoListele";
    Layout = "~/Areas/Yonetim/Views/Shared/_Layout.cshtml";
}

<h2>FotoListele</h2>


<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.BuyukYol)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.BuyukYol)
        </td>
    </tr>
}

</table>

1 Ответ

0 голосов
/ 11 марта 2020

У вас есть два типа моделей.

Родитель: @model IEnumerable<Tututuncu.Models.Urun> Частичное: @model IEnumerable<Tututuncu.Models.UrunFoto>

Вы звоните Частично, используя @Html.Partial("FotoListele") Вы можете использовать @Html.Partial("FotoListele", THE-NEW-MODEL-OF-LIST-UrunFoto)

При использовании Partial без передачи новой модели, она использует родительскую модель. Таким образом, он получает исключение при попытке выполнить приведение.

Вы можете создать новую модель, которая соответствует частичным потребностям, или принять родительскую модель.

Примечание: partial class не имеет отношения к бритвенному двигателю Html .Partial. подробнее об этом Здесь

...