c# - 调用 get 操作时未设置 ViewBag 属性
问题描述
在 MVC 项目中,EF DB 首先,我使用 ViewBag 属性在下拉列表中显示值列表。这是我的 get 方法和 post 方法。-
[ HttpGet]
public ActionResult Create()
{
using (var context = new AdventureWorksEntities())
{
ViewBag.Colors = new SelectList(context.Products.Select(a =>
a.Color).Distinct().ToList());
}
return View();
[HttpPost]
[ActionName("Create")]
public ActionResult CreatePost()
{
var producttocreate = new Product();
try
{
UpdateModel(producttocreate);
if (ModelState.IsValid)
{
using (var context = new AdventureWorksEntities())
{
context.Products.Add(producttocreate);
context.SaveChanges();
}
return RedirectToAction("Index");
}
return View(producttocreate);
}
catch(Exception e)
{
return View(producttocreate);
}
}
这里的属性 ViewBag.Colors 是有问题的属性。当我在 Post 上遇到异常时,我想传递模型并再次返回相同的 Create 视图。但是,即使每次调用 Create Get 方法时我都有设置 ViewBag.Colors 的代码,但它没有被设置,并且在 Create View 呈现时出现错误 -
具有键 'Color' 的 ViewData 项属于 'System.String' 类型,但必须属于 'IEnumerable' 类型。
我确实在其他一些帖子中发现此异常的原因是 ViewBag.Colors 为 null ,但我不明白为什么。为什么从 Post Action 方法调用 View 时没有设置它?解决方案是什么?
解决方案
前
return View(producttocreate);
这样做
ViewData["Colors"] = new SelectList(_context.Products, "Id", "Color", ColorId);
推荐阅读
- django - 如何配置 AWS API Gateway 以获取 pdf 响应?
- java - 根据提供的 Long 值评估在表单中输入的大于比较。MySQL/Java
- java - 在 Java selenium webdriver 中 - 有没有办法让备用列作为 webtable 的标题
- spring-boot - 为什么这个基于 Gradle 的 Spring Boot 项目在 IntelliJ 中运行时不提供静态资源
- dll - 对于解决方案中的不同配置,如何为解决方案中的项目指定不同的构建类型(DLL 或静态库)?
- bash - 如何从 postgres bash 中获取 bash 变量?
- node.js - req.user 和 req.isAuthenticated() 有什么区别
- powershell - psObject 的两个不同输出
- r - 使用 ggplot2 创建堆叠条形图的最简单方法是什么?
- node.js - GCP 上的 docker 映像(nodejs 应用程序)返回 ERR_CONNECTION_REFUSHED(在本地工作)