【问题标题】:InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.AspNetCore.Mvc.RedirectToActionResult',InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“Microsoft.AspNetCore.Mvc.RedirectToActionResult”,
【发布时间】:2022-01-17 11:54:10
【问题描述】:

我正在学习 Asp.net Core 并使用 CRUD 操作、SQL 服务器和使用实体框架构建一个简单的 Web。

当我尝试添加新产品来测试它时,我遇到了这个错误,我尝试了很多方法来解决它,但没有任何改变,所以我需要找出问题所在,我知道它在 actionResult Add 和 Add view 之间:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.AspNetCore.Mvc.RedirectToActionResult', but this ViewDataDictionary instance requires a model item of type 'StockApp.Models.Product'.

这是我的产品模型:

    using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore;
using System.ComponentModel.DataAnnotations;
using FluentValidation;

namespace StockApp.Models
{
    [Table("Products", Schema = "dbo")]
    public class Product
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Display(Name = "Product ID")]
        public int ProductId { get; set; }


        [Required]
        [Column(TypeName = "varchar(150)")]
        [Display(Name = "Product Name")]
        public string ProductName { get; set; }

        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}")]
        [Display(Name = "Prodution Date")]
        public DateTime ProductionDate { get; set; }


        [Required]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}")]
        [Display(Name = "Expiration Date")]
        public DateTime ExpirationDate { get; set; }


        [Required]
        [Column(TypeName = "decimal(12,2)")]
        [Display(Name = "Price")]
        public decimal Price { get; set; }



        //Category model/table

        [ForeignKey("Category")]
        [Required]
        public int CategoryId { get; set; }

        [Display(Name = "Category")]
        [NotMapped]
        public string CategoryName { get; set; }

        public virtual Category Category { get; set; }




        Factory model/table

        [ForeignKey("Factory")]
        [Required]
        public int FactoryId { get; set; }

        [Display(Name = "Made By")]
        [NotMapped]
        public string FactoryName { get; set; }

        public virtual Factory Factory { get; set; }









    }

}    

那是我的 ProductController:

    using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using StockApp.Data;
using StockApp.Models;
using System.Linq;

namespace StockApp.Controllers
{
    public class ProductController : Controller
    {
        private readonly StockDbContext _dbContext;


        public ProductController(StockDbContext dbContext)
        {
            _dbContext = dbContext;
        }



        // GET: ProductController
        public IActionResult Index()
        {
            //var productDbContext = _dbContext.Products.Include(e => e.Category) .Include(e => e.Factory);
            //return View(productDbContext.ToList());

            var productss = (from Product in _dbContext.Products
                             join Category in _dbContext.Categories on Product.ProductId equals Category.CategoryId
                             join Factory in _dbContext.Factories on Product.ProductId equals Factory.FactoryId
                             select new Product
                             {
                                 ProductId = Product.ProductId,
                                 ProductName = Product.ProductName,
                                 ProductionDate = Product.ProductionDate,
                                 ExpirationDate = Product.ExpirationDate,
                                 CategoryId = Product.CategoryId,
                                 CategoryName = Category.CategoryName,
                                 FactoryId = Product.FactoryId,
                                 FactoryName = Factory.FactoryName




                             }).ToList();
            return View(productss);
        }

         

        // GET: ProductController/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }





        // GET: ProductController/Create
        public IActionResult Add()
        {
            ViewBag.Category = this._dbContext.Categories.ToList();
            ViewBag.Factory = this._dbContext.Factories.ToList();
            return View();
        }

        // POST: ProductController/Create
        [HttpPost]
        public IActionResult Add(Product model)
        {
            ModelState.Remove("Category");
            ModelState.Remove("CategoryName");
            ModelState.Remove("Factory");
            ModelState.Remove("FactoryName");
            if (ModelState.IsValid)
            {
                _dbContext.Products.Add(model);
                _dbContext.SaveChanges();
                return View(RedirectToAction("Index"));
            }
            ViewBag.Category = _dbContext.Categories.ToList();
            ViewBag.Factory = _dbContext.Factories.ToList();
            return View("Add", model);
        }




        // GET: ProductController/Edit/5
        public IActionResult Edit(int id)
        {
            return View();
        }

        // POST: ProductController/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: ProductController/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: ProductController/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, IFormCollection collection)
        {
            try
            {
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
}

添加视图:

@model Product



@{
    ViewBag.Title = "Add";
}

<h2>@ViewBag.Title Product</h2>

<h4>Product</h4>
<div class="row">
    <div class="col-md-4">
        <form asp-action=@ViewBag.Title>
            <div asp-validation-summary=All class="text-danger"></div>
            <div class="form-group">
                <label asp-for="ProductName" class="control-label"></label>
                <input asp-for="ProductName" class="form-control" />
                <span asp-validation-for="ProductName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ProductionDate" class="control-label"></label>
                <input asp-for="ProductionDate" class="form-control" />
                <span asp-validation-for="ProductionDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ExpirationDate" class="control-label"></label>
                <input asp-for="ExpirationDate" class="form-control" />
                <span asp-validation-for="ExpirationDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="CategoryId" class="control-label"></label>
                <select asp-for="CategoryId"  asp-items="@(new SelectList(ViewBag.Category,"CategoryId","CategoryName"))" class ="form-control"></select>
            </div>
            <div class="form-group">
                <label asp-for="FactoryId" class="control-label"></label>
                <select asp-for="FactoryId"  asp-items="@(new SelectList(ViewBag.Factory,"FactoryId","FactoryName"))" class ="form-control"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

索引视图:

@model IEnumerable<StockApp.Models.Product>

@{
    ViewBag.Title = "Product";
}

<h1>All Productts</h1>

<p>
    <a asp-action="Add" class="btn btn-outline-primary">Add New Product</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ProductName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ProductionDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ExpirationDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CategoryName)
            </th>
            
           <th>
                @Html.DisplayNameFor(model => model.FactoryName)
            </th>
            
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ProductName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProductionDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ExpirationDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CategoryName)
            </td>
            
            <td>
                @Html.DisplayFor(modelItem => item.FactoryName)
            </td>
           
            <td>
                <a asp-action="Edit" asp-route-id="@item.ProductId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ProductId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.ProductId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-core .net-core asp.net-web-api


    【解决方案1】:

    InvalidOperationException:传递到 ViewDataDictionary 的模型项属于“Microsoft.AspNetCore.Mvc.RedirectToActionResult”类型,但此 ViewDataDictionary 实例需要一个“StockApp.Models.Product”类型的模型项。

    这是因为您在操作中使用了return View(RedirectToAction("Index"));Create。尝试使用return RedirectToAction("Index"); 替换return View(RedirectToAction("Index"));

    【讨论】:

    • 哈哈,看得很清楚,我正在写一个答案在这一分钟:)
    猜你喜欢
    • 2020-01-12
    • 2020-05-13
    • 2020-05-10
    • 1970-01-01
    • 2022-08-03
    • 2022-06-27
    • 2022-01-19
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多