InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为 'Microsoft.AspNetCore.Mvc.RedirectToActio



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

当我试图添加新产品来测试它时,我发现了这个错误。我尝试了很多方法来解决它,但都没有改变,所以我需要弄清楚问题出在哪里,我知道它介于actionResult add和add视图之间:

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




}
}    

那是我的产品控制器:

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>

InvalidOperationException:传递到ViewDataDictionary的模型项的类型为"Microsoft.AspNetCore.Mvc.RegrectToActionResult",但此ViewDataDiction实例需要类型为"StockApp.Models.Product"的模型项。

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

相关内容

最新更新